如何通过布尔列聚合数据框架和总和?



我有这个df,我想聚合它,以便最后两列之和,并减少每个用户id的重复。

目前

user_id | name | product | ...| purchase_flag | retention_flag
123     | John | book    | ...| 0             | 1
123     | John | book    | ...| 1             | 0
....

期望状态

user_id | name | product | ...| purchase_flag | retention_flag
123     | John | book    | ...| 1             | 1
....

我总共有100列,因此在pandas中手动执行groupby是不可行的。我如何按df中的所有列分组,然后按purchase_flag和retention_flag求和?

我尝试:

df.groupby([how to put all cols here expect the flag columns?]).agg({'purchase_flag':'sum','retention_flag':'sum',})

我怎么完成这个?

如果在列表推导中dict中不存在,则可以过滤所有列名:

d = {'purchase_flag':'sum','retention_flag':'sum'}
df = df.groupby([c for c in df.columns if c not in d], as_index=False).agg(d)
print (df)
user_id  name product  purchase_flag  retention_flag
0      123  John    book              1               1

最新更新