我有一个主数据框df:
Colour Item Price
Blue Car 40
Red Car 30
Green Truck 50
Green Bike 30
然后我有了一个价格校正数据帧df_pc:
Colour Item Price
Red Car 60
Green Bike 70
我想说的是,如果价格校正数据框中的“颜色”和“项目”匹配,请替换主DF中的价格。所以预期的输出是;
Colour Item Price
Blue Car 60
Red Car 30
Green Truck 50
Green Bike 70
我目前找不到这样做的方法
答案 0 :(得分:3)
使用Index.isin
过滤掉不匹配的行,然后过滤DataFrame.combine_first
:
df = df.set_index(['Colour','Item'])
df_pc = df_pc.set_index(['Colour','Item'])
df_pc = df_pc[df_pc.index.isin(df.index)]
df = df_pc.combine_first(df).reset_index()
print (df)
Colour Item Price
0 Blue Car 40.0
1 Green Bike 70.0
2 Green Truck 50.0
3 Red Car 60.0
另一项数据测试:
print (df_pc)
Colour Item Price
0 Red Car 60
1 Orange Bike 70 <- not matched row
df = df.set_index(['Colour','Item'])
df_pc = df_pc.set_index(['Colour','Item'])
df_pc = df_pc[df_pc.index.isin(df.index)]
df = df_pc.combine_first(df).reset_index()
print (df)
Colour Item Price
0 Blue Car 40.0
1 Green Bike 30.0
2 Green Truck 50.0
3 Red Car 60.0
答案 1 :(得分:2)
这是使用navigation
的方法:
this.props
combine_first()
编辑: 如果您只想要匹配的项目,我们还可以将其与fillna结合使用:
df_pc.set_index(['Colour','Item']).combine_first(
df.set_index(['Colour','Item'])).reset_index()
Colour Item Price
0 Blue Car 40.0
1 Green Bike 70.0
2 Green Truck 50.0
3 Red Car 60.0