【发布时间】: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