使用 pandas 循环读取CSV文件,然后将它们串联 [英] Reading CSV files in a loop using pandas, then concatenating them
问题描述
我有10个csv文件,分别名为data_run1_all.csv
,data_run2_all.csv
,...,data_run10_all.csv
. CSV文件具有相同的列,但具有不同的行.
I have 10 csv files, named data_run1_all.csv
, data_run2_all.csv
, ..., data_run10_all.csv
. CSV files have same columns, but different rows.
现在,我将它们逐一导入到df_run1
,df_run2
,...,df_run10
.
Now I am importing them one by one to df_run1
, df_run2
, ..., df_run10
.
我可以使用循环导入它们吗?类似于i=1 to 10, df_runi=pandas.read_csv('data_runi_all.csv')
.
Can I use a loop to import them? Something like: i=1 to 10, df_runi=pandas.read_csv('data_runi_all.csv')
.
我之所以问是因为每个数据框的数据分析,绘图等也是相同的.每个数据帧的所有代码重复10次.如果我可以使用循环执行10次,则代码将更短并且可读性更高.
I am asking because the data analysis, plotting, etc. for each data frame are same, too. All the code for each data frame is repeated 10 times. If I can use a loop to do 10 times, the code will be much shorter and readable.
推荐答案
循环读取您的CSV并调用pd.concat
:
Read your CSVs in a loop and call pd.concat
:
file_name = 'data_run{}_all.csv'
df_list = []
for i in range(1, 11):
df_list.append(pd.read_csv(file_name.format(i))
df = pd.concat(df_list)
或者,您可以在理解范围内构建列表:
Alternatively, you could build the list inside a comprehension:
file_name = 'data_run{}_all.csv'
df = pd.concat([pd.read_csv(file_name.format(i)) for i in range(1, 11)])
这篇关于使用 pandas 循环读取CSV文件,然后将它们串联的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!