【问题标题】:Merge dfs in a dictionary based on a column key根据列键合并字典中的dfs
【发布时间】:2026-02-14 20:15:01
【问题描述】:

我有一个这样的字典:{key_1: pd.Dataframe, key_2: pd.Dataframe, ...}。

字典中的每个 dfs 都有一个名为“ID”的列。

并非所有实例都出现在每个数据帧中,这意味着数据帧的大小不同。

无论如何我可以将它们组合成一个大数据框吗?

这是数据的最小可重现示例:


data1 = [{'ID': 's1', 'country': 'Micronesia', 'Participants':3},
        {'ID':'s2', 'country': 'Thailand', 'Participants': 90},
        {'ID':'s3', 'country': 'China', 'Participants': 36},
        {'ID':'s4', 'country': 'Peru', 'Participants': 30}]
 

data2 = [{'ID': '1', 'country': 'Micronesia', 'Kids_per_participant':3},
        {'ID':'s2', 'country': 'Thailand', 'Kids_per_participant': 9},
        {'ID':'s3', 'country': 'China', 'Kids_per_participant': 39}]


data3= [{'ID': 's1', 'country': 'Micronesia', 'hair_style_rank':3},
        {'ID':'s2', 'country': 'Thailand', 'hair_style_rank': 9}]

df1 = pd.DataFrame(data1)  
df2 = pd.DataFrame(data2)
df3 = pd.DataFrame(data3)

dict_example={'df1_key':df1,'df2_key':df2,'df3_key':df3}

pd.merge(dict_example.values(), on="ID", how="outer")

【问题讨论】:

  • 谢谢! @EoinS 的回答对我有用。我编辑我的问题只是为了创建一个更清晰的数据集变量示例。

标签: python pandas dataframe dictionary merge


【解决方案1】:

对于具有任意数量键的dict,您可以这样做

i=list(dict_example.keys())
newthing = dict_example[i[0]]
for j in range(1,len(i)):
  newthing = newthing.merge(dict_example[i[j]],on='ID', how = 'outer')

首先列出您的数据框。其次创建一个first DataFrame。然后遍历其余的 DataFrame 和 merge 之后的每个。我确实注意到每个ID 都有country,但它没有在您最初的on 声明中列出。你也想加入country吗?如果是这样,将上面的合并替换为将连接条件更改为包含country的列表

newthing = newthing.merge(dict_example[i[j]],on=['ID','country'], how = 'outer')

Documentsmerge

如果你不关心改变你的 DataFrames 代码可以像这样更短

for j in range(1,len(i)):
  df1 = df1.merge(dict_example[i[j]],on=['ID','country'], how = 'outer')

【讨论】: