我有一個(gè)主df欄,其中一欄我想用第二欄的值進(jìn)行更新df1。對(duì)我來(lái)說(shuō),最棘手的部分是我需要從每個(gè)df匹配2個(gè)公共列,才能知道要更新哪個(gè)值。使用示例: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貢獻(xiàn)1829條經(jīng)驗(yàn) 獲得超4個(gè)贊
你可以用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

呼喚遠(yuǎn)方
TA貢獻(xiàn)1856條經(jīng)驗(yàn) 獲得超11個(gè)贊
通過(guò)numpy.where
與我從@jezrael的解決方案中找到的三元運(yùn)算符一起使用。
df['col3'] = np.where(df['col1'].isin(df1['col1']) & df['col2'].isin(df1['col2']), df1['col3'], df['col3'])
添加回答
舉報(bào)
0/150
提交
取消