【问题标题】:Use a loop to stack data frames generated from a loop使用循环堆叠从循环生成的数据帧
【发布时间】:2020-03-04 01:11:55
【问题描述】:

我正在使用循环来生成具有所有相同列名的数据框,并且我想将它们堆叠在一起。 (如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 多个数据帧,我想将它们堆叠在一起。

【问题讨论】:

  • 看看你的第一个循环,除了最后一个 DataFrame 之外,你都丢失了。

标签: python pandas dataframe


【解决方案1】:

考虑使用列表理解构建一个数据框列表,然后在任何循环之外将列表传递给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)

【讨论】:

    猜你喜欢
    • 2020-08-14
    • 2021-04-24
    • 2020-12-06
    • 2012-12-11
    • 1970-01-01
    • 1970-01-01
    • 2021-11-16
    • 2018-11-13
    • 1970-01-01
    相关资源
    最近更新 更多