【问题标题】:Python Append dataframe generated in nested loopsPython Append 在嵌套循环中生成的数据帧
【发布时间】:2021-02-22 17:20:55
【问题描述】:

我的程序有两个for 循环。我在每个循环中生成一个 df 。我想附加这个结果。对于内部循环的每次迭代,都会生成 1 行 24 列的数据。对于外循环的每次迭代,它会生成 8 行 24 列的数据。我在以正确的方式追加时遇到问题,因此最终数据框有 8 行和 24 列。 我的代码:

biglist = []
# The actual code is bigger. Below is representation of it.
for i in range (x1,...,x8):
   tem_list = []
   for j in range ([y1,y2,y3],[y4,..]...[y22,y23,y24]):
       tem_df = pd.DataFrame({'y1':[value1],'y2':[value2],'y3':[value3]},index=i)
       tem_list.append(tem_df)
   biglist.append(tem_list)
# convert listss of lists in biglist to a simple list of dfs
biglist1 = [item for sublist in biglist for item in sublist]
df = pd.concat(biglist1)
print(df)

目前的输出:

# below is actual output of my dataframe: 
      Pmpp_loss Pmpp_delmt  ... Rsh_delmt Rsh_desen
s1    17.0326    42.5349  ...       NaN       NaN
s2        NaN        NaN  ...       NaN       NaN
s3        NaN        NaN  ...       NaN       NaN
s4        NaN        NaN  ...       NaN       NaN
s5        NaN        NaN  ...       NaN       NaN
s6        NaN        NaN  ...       NaN       NaN
s7        NaN        NaN  ...       NaN       NaN
s8        NaN        NaN  ...   92.1853 -0.444959

[8 rows x 192 columns]

在上面,8 行是正确的。但我得到了 192 列,而不是 24 列。在这里,24 列重复了 8 次。这就是我们在这里看到许多 NaN 的原因。

【问题讨论】:

标签: python pandas list dataframe for-loop


【解决方案1】:

试试:

  • 将此biglist.append(tem_list) 更改为:biglist.append(pd.concat(tem_list))

  • 删除此行:biglist1 = [item for sublist in biglist for item in sublist]

  • 把这个df = pd.concat(biglist1)修改成df = pd.concat(biglist)


如果你已经定义了列名,你也可以在你的循环范围之外创建一个空的DataFrame,并从你的内部循环中直接将数据附加到它上面:

# Before loop
colnames = ['y1', 'y2', 'y3']
df = pd.DataFrame(data=None, columns=colnames)

将附加行更改为内部循环中的单个行:

df = df.append(tem_df)

不需要使用biglisttem_listpd.concat


用户 cmets 后编辑

biglist = []
for i in range (x1,...,x8):
    for j in range ([y1,y2,y3],[y4,..]...[y22,y23,y24]):
        tem_df = pd.DataFrame({'y1':[value1],'y2':[value2],'y3':[value3]},index=i)
    biglist.append(pd.concat(tem_df),axis=1)
df = pd.concat(biglist)
print(df)

【讨论】:

  • 使用上面的代码biglist.append(pd.concat(tem_list)),现在我得到了[64 rowsx24 columns]的df。列是正确的,但行是重复的。
  • 关于您提供的解决方案的第二部分,我没有事先创建 df 的列名。所以,我只需要从那里获取列名。否则,我必须编写另一组代码来获取列名并创建一个空数据框。
  • 好的,看来你的每个循环都运行了 8 次。我不知道这是否有意义,但是如果您将标识从tem_list.append(tem_df) 删除到外循环呢?
  • 无论如何,请在编辑后测试解决方案。
  • 你知道吗,经过简单的编辑,我就可以正常工作了。我编辑了你的解决方案。我只需要在附加之前连接 tem_df。有效。我得到了 [8 rowsx24columns]。非常感谢。
猜你喜欢
  • 2017-03-27
  • 1970-01-01
  • 2021-07-07
  • 1970-01-01
  • 2021-10-03
  • 2012-12-02
  • 1970-01-01
  • 2021-10-18
相关资源
最近更新 更多