【发布时间】: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 之外,你都丢失了。