[英]Pandas - Update/Replace Values in Column with values from another DF (based on 2 matching columns)
我有一個主df
,其中有一列我想用第二個df1
值進行更新。
對我來說,最棘手的部分是,我需要在每個df的2個公共列上進行匹配,才能知道要更新哪個值。
使用示例:
df col1 col2 col3
1 1A Z4 4
2 1B Z5 2
3 1C Z6 7
4 1D Z7 1
5 1E Z12 9
df1 col1 col2 col3
1 1G Z9 1
2 1B Z5 2
3 1C Z6 3
4 1D Z7 4
5 1E Z8 5
輸出:
df col1 col2 col3
1 1A Z4 4 (no match, no update)
2 1B Z5 2 (match, updated)
3 1C Z6 3 (match, updated)
4 1D Z7 4 (match, updated)
5 1E Z12 9 (not matched on both, no update)
謝謝您的幫助。
您可以將set_index
與update
set_index
使用
df1=df1.set_index(['col1','col2'])
df1.update(df2.set_index(['col1','col2']))
df1.reset_index(inplace=True)
df1
Out[528]:
col1 col2 col3
0 1A Z4 4.0
1 1B Z5 2.0
2 1C Z6 3.0
3 1D Z7 4.0
4 1E Z12 9.0
通過使用numpy.where
以及從@jezrael的解決方案中找到的三元運算符。
df['col3'] = np.where(df['col1'].isin(df1['col1']) & df['col2'].isin(df1['col2']), df1['col3'], df['col3'])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.