熊猫条件地图/填充/替换

时间:2019-05-10 06:00:13

标签: python pandas

d1=pd.DataFrame({'x':['a','b','c','c'],'y':[-1,-2,-3,0]})
d2=pd.DataFrame({'x':['d','c','a','b'],'y':[0.1,0.2,0.3,0.4]})

我想用d2中的对应d1.y替换y <0的y。就像Excel中的vlookup一样。核心问题是根据x替换y而不是简单地操纵y。我想要的是

Out[40]: 
   x    y
0  a  0.3
1  b  0.4
2  c  0.2
3  c  0.0

2 个答案:

答案 0 :(得分:3)

在条件下使用Series.map

s = d2.set_index('x')['y']
d1.loc[d1.y < 0, 'y'] = d1['x'].map(s)
print (d1)

   x    y
0  a  0.3
1  b  0.4
2  c  0.2
3  c  0.0

答案 1 :(得分:1)

您可以尝试以下方法:

d1.loc[d1.y < 0, 'y'] = d2.loc[d1.y < 0, 'y']

相关问题