如何用Pandas按id1和id2分组统计布尔值及组合类型数量?
Pandas分组统计实现方案
原始数据
首先定义输入的DataFrame:
import pandas as pd df = pd.DataFrame( [["A",20,True],["C",21,True],["B",20,False],["A",21,False],["B",20,False],["A",20,False]], columns=["id1","id2","val1"] )
原始数据展示:
| id1 | id2 | val1 |
|---|---|---|
| A | 20 | True |
| C | 21 | True |
| B | 20 | False |
| A | 21 | False |
| B | 20 | False |
| A | 20 | False |
需求说明
- 按
id1和id2分组,统计每组中True和False的总数,生成df_out1; - 统计
id1+id2的组合类型数量:全为True、全为False、同时包含True和False,生成df_out2。
1. 生成分组的True/False计数(df_out1)
利用groupby结合agg方法,直接统计每组中True的数量(布尔值求和等价于计数True),再通过组内总长度减去True的数量得到False的数量:
df_out1 = df.groupby(["id1", "id2"])["val1"].agg( Total_True="sum", Total_False=lambda x: len(x) - x.sum() ).reset_index()
输出结果:
| id1 | id2 | Total_True | Total_False |
|---|---|---|---|
| A | 20 | 1 | 1 |
| A | 21 | 0 | 1 |
| B | 20 | 0 | 2 |
| C | 21 | 1 | 0 |
2. 统计组合类型数量(df_out2)
先对每个分组判断是否包含True或False,再映射为对应的类型,最后统计各类型的数量:
# 判断每个分组是否包含True和False grouped = df.groupby(["id1", "id2"])["val1"].agg( has_true=lambda x: x.any(), has_false=lambda x: (~x).any() ) # 映射分组类型 def map_group_type(row): if row["has_true"] and not row["has_false"]: return "All_True" elif not row["has_true"] and row["has_false"]: return "All_False" else: return "Both_TrueFalse" grouped["Type"] = grouped.apply(map_group_type, axis=1) # 统计各类型数量并调整顺序 df_out2 = grouped["Type"].value_counts().reset_index(name="Total_id") # 按预期顺序重新排列 df_out2 = df_out2.set_index("Type").reindex(["All_True", "All_False", "Both_TrueFalse"]).reset_index()
输出结果:
| Type | Total_id |
|---|---|
| All_True | 1 |
| All_False | 2 |
| Both_TrueFalse | 1 |
内容的提问来源于stack exchange,提问作者Chethan
相关产品推荐
相关产品推荐

