我有2个数据帧df1和df2,都具有列“ A”,“ count”。我想基于列A加入这些,然后如果列相同则从这些行中减去计数。例如:
df1
A count
s1 10
s2 5
s3 3
s4 7
df2
A count
s1 2
s4 4
我的最终输出应该是
combined
A count1 count2 change
s1 10 2 8 // count1-count2
s2 5 none none
s3 3 none none
s4 7 4 3
答案 0 :(得分:1)
您可以执行外部合并,然后进行计算:
res = pd.merge(df1.rename(columns={'count': 'count1'}),
df2.rename(columns={'count': 'count2'}), how='outer')\
.eval('change = count1 - count2')
print(res)
A count1 count2 change
0 s1 10 2.0 8.0
1 s2 5 NaN NaN
2 s3 3 NaN NaN
3 s4 7 4.0 3.0