根据列键在字典中合并 dfs

Merge dfs in a dictionary based on a column key

我有这样的字典:{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")

对于具有任意数量键的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')