Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
435 views
in Technique[技术] by (71.8m points)

python - Reading CSV files in a loop using pandas, then concatenating them

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.

Now I am importing them one by one to df_run1, df_run2, ..., df_run10.

Can I use a loop to import them? Something like: i=1 to 10, df_runi=pandas.read_csv('data_runi_all.csv').

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)])

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...