Pandas-使用来自另一个DF的值更新/替换列中的值(基于2个匹配的列)

时间:2018-07-26 03:57:06

标签: python pandas

我有一个主要的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)

谢谢您的帮助。

2 个答案:

答案 0 :(得分:2)

您可以将set_indexupdate一起使用

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

答案 1 :(得分:0)

通过使用numpy.where以及我从@jezrael的解决方案中找到的三元运算符。

df['col3'] = np.where(df['col1'].isin(df1['col1']) & df['col2'].isin(df1['col2']), df1['col3'], df['col3'])
相关问题