输入:
df1=pd.DataFrame({
"BusId":['abc1','abc2','abc3'],
"Fair Increase":[2,3,5]
})
df2=pd.DataFrame({
'BusId':['abc1','abc2','abc3','abc4','abc5'],
"Fair":[5,6,7,8,9]
})
仅需要针对df2上df1中存在的 BusId 进行计算。
计算增加的公平 df2公平+ df1公平增长
预期输出:
BusId Fair Increased Fair
abc1 5 7
abc2 6 9
abc3 7 12
答案 0 :(得分:3)
您可以将map
用于字典查找
m = dict(df2.values)
df1.assign(**{'Increased Fair': df1.BusId.map(m) + df1['Fair Increase']})
BusId Fair Increase Increased Fair
0 abc1 2 7
1 abc2 3 9
2 abc3 5 12
答案 1 :(得分:1)
您可以使用df.merge
合并df2和df2,创建新列Increased Fair
并删除旧列Fair Increase
>>> df3 = df2.merge(df1).set_index('BusId')
>>> df3['Increased Fair'] = df3['Fair'] + df3['Fair Increase']
>>> del df3['Fair Increase']
>>> df3
Fair Increased Fair
BusId
abc1 5 7
abc2 6 9
abc3 7 12