使用循环来堆叠循环产生的数据帧

时间:2020-03-04 01:11:55

标签: python pandas dataframe

我正在使用循环来生成具有所有相同列名的数据帧,我想将它们堆叠在一起。 (如this网页所示)


#here's a list I use to read my data frames 
#(the csv files I'm working on have a name convention that I need to follow.)
title_cn = [1, 2, 3]
title_tn = [22, 27, 31]

#here's the for loop I used to generate data frames called df 
for (i, j) in zip(title_cn, title_tn): 
    filename = '{}_Cycle_{}_Test.csv'.format(i, j)
    reading = pd.read_csv(filename)
    df = pd.DataFrame(reading)  

#now I want to stack the 'df' together in 'Joined_dataframe'  
for k in title_cn:
    Joined_dataframe = pd.concat(df)

从上面的代码中,我有3个数据帧。我想使用pd.concat

将它们粘合在一起

我认为我的问题是我不知道如何正确编写第二个循环。到目前为止,我只得到了for循环生成的最后一个数据帧。否则,我将得到重复的数据帧,作为第一个for循环的其余部分。

我尝试搜索,但是大多数教程都在谈论使用一个循环来生成缝合数据帧(没有前面的for循环)。我觉得自己走在正确的道路上,但我不知道该怎么做才能继续前进。

我希望使用循环,因为实际上我有20多个数据帧要堆叠在一起。

1 个答案:

答案 0 :(得分:2)

考虑使用列表理解功能构建数据帧列表,然后将列表传递到concat 一次(在任何循环之外):

df_list = [pd.DataFrame('{}_Cycle_{}_Test.csv'.format(i, j)) \
              for (i, j) in zip(title_cn, title_tn)]

final_df = pd.concat(df_list, ignore_index = True)