用另一个表列更新一列,其中表的另一列彼此相等

时间:2019-04-05 11:45:42

标签: pandas

我有两个如下的熊猫数据框,

Left_Frame 
       symbol    price timelab1 timelab2 timelab3     _merge
    0  145822  10.5018    19:00                    left_only
    1  145819  10.5055    19:00                    left_only
Right_Frame
        symbol  price timelab1 timelab2 timelab3      _merge
    16  145822  10.58      NaN      NaN      NaN  right_only
    17  145819  10.55      NaN      NaN      NaN  right_only

我要用Left_Frame的价格更新Right_Frame的价格,其中symbol等于两个数据帧。 预期结果是

Left_Frame 
       symbol    price timelab1 timelab2 timelab3     _merge
    0  145822  10.58      19:00                    left_only
    1  145819  10.55      19:00                    left_only

我如何能做到这一点的熊猫?

2 个答案:

答案 0 :(得分:2)

这可以完成工作

  

我想用Right_Frame价格更新其中的Left_Frame价格,其中符号   等于两个数据帧。预期结果是

left_frame['price'] = np.where(left_frame['symbol'].values == right_frame['symbol'].values, right_frame['price'],left_frame['price'])

更新

left_frame.loc[:,'price'] = np.where(left_frame['symbol'].values == right_frame['symbol'].values, right_frame['price'],left_frame['price'])

答案 1 :(得分:1)

Series.mapDataFrame.set_index创建的另一个Series一起使用,对于不匹配的值,将Series.fillna替换为原始值:

print (Left_Frame)
   symbol  price timelab1  timelab2  timelab3     _merge
0  145822     12    19:00       NaN       NaN  left_only
1  100000     13    19:00       NaN       NaN  left_only


print (Right_Frame)
    symbol  price  timelab1  timelab2  timelab3      _merge
16  145822     10       NaN       NaN       NaN  right_only
17  145819     18       NaN       NaN       NaN  right_only

s = Right_Frame.set_index('symbol')['price']
Left_Frame['price'] = Left_Frame['symbol'].map(s).fillna(Left_Frame['price'])

#slowier alternative
#Left_Frame['price'] = Left_Frame['symbol'].replace(s)

print (Left_Frame)
   symbol  price timelab1  timelab2  timelab3     _merge
0  145822   10.0    19:00       NaN       NaN  left_only
1  100000   13.0    19:00       NaN       NaN  left_only