Python 如何将作为字典键存储的数据帧连接到单个数据帧中?
我有一个有120个键的字典,每个键包含一个数据帧。如何以编程方式将这些值连接(使用Python 如何将作为字典键存储的数据帧连接到单个数据帧中?,python,pandas,Python,Pandas,我有一个有120个键的字典,每个键包含一个数据帧。如何以编程方式将这些值连接(使用pd.concat)到单个大数据帧中?只需使用pd.concat(d.values())将字典中的值连接起来即可。: 上面的答案与将dict中的每个df添加到一个列表中,然后将它们连接起来有什么区别吗list_of_dfs=[]for key in dict_of_dfs.keys():list_of_dfs.append(dict_of_dfs[key])df_total=pd.concat(list_of_df
pd.concat
)到单个大数据帧中?只需使用pd.concat(d.values())将字典中的值连接起来即可。
:
上面的答案与将dict中的每个df添加到一个列表中,然后将它们连接起来有什么区别吗
list_of_dfs=[]for key in dict_of_dfs.keys():list_of_dfs.append(dict_of_dfs[key])df_total=pd.concat(list_of_dfs)
我认为唯一的区别是您正在添加一个列表的创建,它使用内存和时间,不创建这些列表可以节省内存和时间
>>> d = {1:pd.DataFrame(np.random.random((5,5))),2:pd.DataFrame(np.random.random((5,5)))}
>>> d
{1: 0 1 2 3 4
0 0.319556 0.540776 0.988554 0.775070 0.535067
1 0.383192 0.379474 0.204998 0.948605 0.785190
2 0.006732 0.362755 0.537260 0.854110 0.409386
3 0.795973 0.073652 0.796565 0.168206 0.814202
4 0.531702 0.524501 0.002366 0.631852 0.024509,
2: 0 1 2 3 4
0 0.369098 0.125491 0.832362 0.183199 0.729110
1 0.069843 0.337424 0.476837 0.078589 0.489447
2 0.504904 0.456996 0.239802 0.025953 0.609697
3 0.262001 0.646389 0.992928 0.124552 0.878561
4 0.707881 0.520429 0.609257 0.018488 0.167053}
>>> new_df = pd.concat(d.values())
>>> new_df
0 1 2 3 4
0 0.319556 0.540776 0.988554 0.775070 0.535067
1 0.383192 0.379474 0.204998 0.948605 0.785190
2 0.006732 0.362755 0.537260 0.854110 0.409386
3 0.795973 0.073652 0.796565 0.168206 0.814202
4 0.531702 0.524501 0.002366 0.631852 0.024509
0 0.369098 0.125491 0.832362 0.183199 0.729110
1 0.069843 0.337424 0.476837 0.078589 0.489447
2 0.504904 0.456996 0.239802 0.025953 0.609697
3 0.262001 0.646389 0.992928 0.124552 0.878561
4 0.707881 0.520429 0.609257 0.018488 0.167053