【发布时间】: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 的原因。
【问题讨论】:
-
请提供minimal reproducible example,以及预期的输出。
标签: python pandas list dataframe for-loop