简体   繁体   中英

Python pd.read_csv: How to read files through a loop?

I would like to be able to read data by using pd.read_csv and store the data in Numpy ndarrays. I have a set of data which includes elements as xN1N1,xN1N2,...,xN1N50 (the general name format is as xN1Ny , for y in range(2,51) ). For each of them, I basically would like to run the following operation:

xN1N1 = pd.read_csv("xN1N1.csv") 
xN1N1 = xN1N1.to_numpy()

To do this with a for loop (I would like to read and save all the elements at one time), I attempted to define a function that would help, as follows:

def data(id_number):
    x1 = pd.read_csv("'xN1N%d' % id_number.csv")
    return x1

Executing this for y in range(2,51) gives me nothing, I am aware that the syntax is extremely defected, but I cannot correct it.

I would appreciate any help on this.

您可以使用 python 字符串格式来解决您的问题。

return pd.read_csv("xN1N{}.csv".format(id_number))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM