繁体   English   中英

如何聚合数据框并按布尔列求和?

[英]How to aggregate dataframe and sum by boolean columns?

我有这个 df 并想聚合它,以便最后 2 列总结并减少每个用户 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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM