我有一个主数据框 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
我目前找不到执行此操作的方法
Use Index.isin http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Index.isin.html过滤掉没有匹配的行,然后DataFrame.combine_first http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.combine_first.html:
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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)