Python 如果另一列';s值在数据帧中相同
我有两个数据帧,df1和df2都有列“A”,“count”。我想根据列A连接这些行,若列相同,则从这些行中减去计数。例如:Python 如果另一列';s值在数据帧中相同,python,pandas,python-2.7,join,Python,Pandas,Python 2.7,Join,我有两个数据帧,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
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
可以执行外部合并,然后执行计算:
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
为什么不
how='left'
?@ycx,因为df2
中可能有一个A
值,而该值不在df1
中。目前尚不清楚是否会出现这种情况,但外部联接通常更安全。@jpp:I get***AttributeError:“builtin\u function\u或\u method”对象没有属性“rename”
看起来您的df1
(或df2
)不是数据帧。检查您的输入。@jpp:哦,是的,对不起,添加了错误的变量名。但是我当前的输出有6列,作为索引A_x count1 A_y count2 change
而不是A count1 count2 change
,并且它不会对同一列A的值进行减法,而是对A的任何值的前4行进行减法。因此,df1的第一行从df2的第一行中减去,df1的第二行从df2的第二行中减去等等。