我有一個像這樣的字典:{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")
uj5u.com熱心網友回復:
對于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')
首先列出您的資料框。其次創建一個firstDataFrame。然后遍歷其余的 DataFrame 以及merge之后的每一個。我確實注意到你有country每個,但它沒有在你的初始宣告ID中列出。on你也想加入country嗎?如果是這樣,將上面的合并替換為將連接條件更改為一個串列,包括country
newthing = newthing.merge(dict_example[i[j]],on=['ID','country'], how = 'outer')
檔案在merge
如果你不關心改變你的 DataFrames 代碼可以像這樣更短
for j in range(1,len(i)):
df1 = df1.merge(dict_example[i[j]],on=['ID','country'], how = 'outer')
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/410016.html
標籤:
