我有两个如下的熊猫数据框,
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
我如何能做到这一点的熊猫?
答案 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.map
与DataFrame.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