[英]Merging Pandas dataframes on column label and overwriting other values in matched rows
[英]Pandas merging dataframes, overwriting values on key
如果這個問題是重復的,我道歉。 我真的找不到這個具體案例的答案。 是否可以合並/連接兩個數據幀,同時如果第二個數據幀中也存在鍵('id'),則覆蓋第一個數據幀中的值? 有點像SQL中的'INSERT - ON DUPLICATE KEY UPDATE'命令。
第一個數據幀'df1':
id value
0 100010 25
1 100011 22
2 100012 30
第二個數據幀'df2':
id value
0 100012 35
1 100013 36
合並數據幀會產生新列,並保留“id”'100012'的舊數據:
df3 = pd.merge(df1, df2, on='id', how='outer')
print(df3)
id value_x value_y
0 100010 25.0 NaN
1 100011 22.0 NaN
2 100012 30.0 35.0
3 100013 NaN 36.0
是否可以直接從合並功能獲得所需的輸出? 所以只更新'id''100012'並添加新行'100013'?
id value
0 100010 25
1 100011 22
2 100012 35
3 100013 36
我嘗試過合並 , 加入 , 更新和combine_first ,都沒有成功。 謝謝你的幫助!
編輯:
最簡單的方法是:
>>> df1=df1.set_index('id')
>>> df2=df2.set_index('id')
在df2
上使用combine_first
>>> df2.combine_first(df1)
value
id
100010 25
100011 22
100012 35
100013 36
老帖子:
作為替代方案,您可以使用標准的python字典
>>> df1=df1.set_index('id')
>>> df2=df2.set_index('id')
用df1
制作一本字典
>>> d = df1.to_dict( 'index' )
>>> d
{'100012': {'value': '30'}, '100010': {'value': '25'}, '100011': {'value': '22'}}
update()
與其他數據幀字典 - 將使用完整行更新重復鍵
>>> d.update( df2.to_dict( 'index' ) )
>>> d
{'100012': {'value': '35'}, '100013': {'value': '36'}, '100010': {'value': '25'}, '100011': {'value': '22'}}
將其轉回數據框:
>>> pd.DataFrame.from_dict( d, 'index' )
value
100010 25
100011 22
100012 35
100013 36
如果你想把它全部放在熊貓里 - 拉斐爾的解決方案更好
只需使用pd.concat
,索引不在df2
的索引中。 讓
df = df.set_index('id')
df2 = df2.set_index('id')
然后
>>> merged = pd.concat([df[~df.index.isin(df2.index)], df2]).reset_index()
id value
0 100010 25
1 100011 22
2 100012 35
3 100013 36
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.