对于A和B相同的每一行,我尝试对列C中的所有值进行减法运算。
我有:
A B C
Car Wheel 4
Car Wheel 2
Plane Motor -10
Plane Motor -5
Plane Wheel 12我需要:
A B C
Car Wheel 4-2 = 2
Plane Motor -10-(-5) = -5
Plane Wheel 12我实际上有一些与df.groupby('A','B').sum()类似的东西,问题是我没有找到减法运算的等价物...pd.sub似乎用于数据帧之间的操作,而不仅仅是在一列上。
发布于 2019-12-24 13:16:31
您可以通过-1聚合sum,只有多个重复的值,因此输出为聚合减法:
print (df.assign(C = np.where(df.duplicated(['A','B']), -1, 1) * df.C))
A B C
0 Car Wheel 4
1 Car Wheel -2
2 Plane Motor -10
3 Plane Motor 5
4 Plane Wheel 12
df1 = (df.assign(C = np.where(df.duplicated(['A','B']), -1, 1) * df.C)
.groupby(['A','B'], as_index=False)['C'].sum())
print (df1)
A B C
0 Car Wheel 2
1 Plane Motor -5
2 Plane Wheel 12https://stackoverflow.com/questions/59464023
复制相似问题