我有一個主df欄,其中一欄我想用第二欄的值進行更新df1。對我來說,最棘手的部分是我需要從每個df匹配2個公共列,才能知道要更新哪個值。使用示例:df col1 col2 col31 1A Z4 42 1B Z5 23 1C Z6 74 1D Z7 15 1E Z12 9df1 col1 col2 col31 1G Z9 12 1B Z5 23 1C Z6 34 1D Z7 45 1E Z8 5輸出:df col1 col2 col31 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)謝謝您的幫助。
2 回答

浮云間
TA貢獻1829條經驗 獲得超4個贊
你可以用set_index與update
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
添加回答
舉報
0/150
提交
取消