You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在Pandas中按多列分组计算通过率的实现方法

Pandas分组计算通过率的正确方法

问题场景

你有一个包含type、location、pass、enrolled列的Pandas DataFrame,示例数据如下:

  1. student、US、yes、highschool
  2. student、CA、yes、highschool
  3. teacher、US、yes、college
  4. teacher、US、no、college
  5. student、US、no、highschool
  6. student、CA、yes、college
  7. 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的输出如下:

typelocationenrolledpass_rate
studentCAcollege0.5
studentCAhighschool1.0
studentUShighschool0.5
teacherUScollege0.5

内容的提问来源于stack exchange,提问作者unlocknew

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 02:57:26