FaC*_*fee 2 python dictionary for-loop dataframe pandas
假设我有一个pandas数据帧字典,其中键是0, 1, 2, ..., 999,而值是像这样的数据帧(test_df):
A B C
0 1.438161 -0.210454 -1.983704
1 -0.283780 -0.371773 0.017580
2 0.552564 -0.610548 0.257276
3 1.931332 0.649179 -1.349062
4 1.656010 -1.373263 1.333079
5 0.944862 -0.657849 1.526811
Run Code Online (Sandbox Code Playgroud)
假设索引对您没有任何意义,并且您希望创建一个新的数据框,其中列A和B连接:
mydf=pd.concat([test_df[0]['A'],test_df[0]['B']], axis=1, keys=['A','B'])
现在,我可以在for循环中使用这一行来迭代我的数据帧字典中的所有键吗?
如果没有,那么另一种方式是什么?结果将是一个包含两列A和B/或6x1000行的数据框.因此,索引列会从去0到5999.
如果df_dic是你的字典,你可以这样做:
pd.concat([df[['A', 'B']] for df in df_dic.values()]).reset_index(drop=True)
Run Code Online (Sandbox Code Playgroud)
如果df_dic包含两个键值对,结果如下: