在Pandas中按多列分组计算通过率的实现方法
Pandas分组计算通过率的正确方法
问题场景
你有一个包含type、location、pass、enrolled列的Pandas DataFrame,示例数据如下:
- student、US、yes、highschool
- student、CA、yes、highschool
- teacher、US、yes、college
- teacher、US、no、college
- student、US、no、highschool
- student、CA、yes、college
- student、CA、no、college
需要按type、location、enrolled三列分组,计算每组的通过率(pass_rate),最终得到包含分组列与pass_rate的结果表。你尝试执行df = df.groupby(["type", "location", "enrolled"]).count().mean(),但仅得到一个整数,需要正确的实现方法。
DataFrame生成代码:
import pandas as pd list_of_dict = [ {"type": "student", "location": "US", "pass": "yes", "enrolled": "highschool"}, {"type": "student", "location": "CA", "pass": "yes", "enrolled": "highschool"}, {"type": "teacher", "location": "US", "pass": "yes", "enrolled": "college"}, {"type": "teacher", "location": "US", "pass": "no", "enrolled": "college"}, {"type": "student", "location": "US", "pass": "no", "enrolled": "highschool"}, {"type": "student", "location": "CA", "pass": "yes", "enrolled": "college"}, {"type": "student", "location": "CA", "pass": "no", "enrolled": "college"}, ] df = pd.DataFrame(list_of_dict)
错误原因
你用的groupby(["type", "location", "enrolled"]).count().mean()逻辑错误:count()会先对每组的各列计数,返回一个包含分组索引的DataFrame;后续的.mean()是对整个计数结果取全局均值,自然只会得到一个单一数值,而非分组的通过率。
正确实现方法
方法1:转换pass列为数值后计算分组均值
将pass列的yes转为1、no转为0,再对分组后的数值列取均值,直接得到通过率:
# 转换pass列为数值类型 df['pass_num'] = df['pass'].replace({'yes': 1, 'no': 0}) # 分组计算通过率并重置索引 result = df.groupby(['type', 'location', 'enrolled'])['pass_num'].mean().reset_index(name='pass_rate')
方法2:分组时直接用agg自定义计算
无需额外列,直接在agg中通过lambda表达式计算每组内yes的占比:
result = df.groupby(['type', 'location', 'enrolled']).agg( pass_rate=('pass', lambda x: (x == 'yes').mean()) ).reset_index()
方法3:利用value_counts的normalize参数
通过value_counts(normalize=True)直接统计每组内pass值的占比,再提取yes对应的比例:
# 分组统计pass值的占比,提取yes的比例并整理格式 result = df.groupby(['type', 'location', 'enrolled'])['pass'].value_counts(normalize=True).unstack().fillna(0)['yes'].reset_index(name='pass_rate')
最终结果
执行任意一种方法后,result的输出如下:
| type | location | enrolled | pass_rate |
|---|---|---|---|
| student | CA | college | 0.5 |
| student | CA | highschool | 1.0 |
| student | US | highschool | 0.5 |
| teacher | US | college | 0.5 |
内容的提问来源于stack exchange,提问作者unlocknew
相关产品推荐
相关产品推荐

