我想知道如何根据另一列的值(0 或 1)对一列求和
id area PP
a 0,95999998 0
a 0,44 1
b 1,6900001 0
c 2 0
d 5,8499999 0
e 0,66000003 1
我可以找到每个id的区域
surface_id = df.groupby("id")["area"].sum()
但我还想要的是 id 的区域,如果 PP = 1 得到这样的东西:
id area_PP
a 0,44
b 0
c 0
d 0
e 0,66000003
最佳答案
一种使用变换但更长的方法
df['area_pp'] = df[df.PP == 1].groupby("id")["area"].transform('sum')
df.fillna(0, inplace = True)
id area PP area_pp
0 a 0,95999998 0 0
1 a 0,44 1 0,44
2 b 1,6900001 0 0
3 c 2 0 0
4 d 5,8499999 0 0
5 e 0,66000003 1 0,66000003
关于 python : Pandas Sum with more than one condition,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46812512/