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

Python Pandas:分组后如何获取唯一学生计数及占比?

按分数段统计唯一学生数及占比的实现方法

原始数据

首先创建示例DataFrame:

import pandas as pd

df = pd.DataFrame({'student': 'AAA AAA BBB BBB BBB CCC DDD DDD DDD DDD'.split(),
                   'grade': ['B', 'B', 'C', 'A', 'A', 'B', 'B', 'A', 'B', 'B']})

输出的原始表格:

student grade
0     AAA     B
1     AAA     B
2     BBB     C
3     BBB     A
4     BBB     A
5     CCC     B
6     DDD     B
7     DDD     A
8     DDD     B
9     DDD     B

需求说明

按grade分组,统计各分数段的唯一学生数量,以及该数量占总学生数(共4名)的百分比,期望输出格式如下:

grade student_count percentage
 A         2           50.00
 B         3           75.00
 C         1           25.00

实现步骤

  1. 先计算总唯一学生数:
total_students = df['student'].nunique()
  1. 分组统计唯一学生数,并计算占比:
# 分组统计并重置索引,命名统计列
result = df.groupby('grade')['student'].nunique().reset_index(name='student_count')
# 计算百分比并保留两位小数
result['percentage'] = (result['student_count'] / total_students * 100).round(2)
  1. 查看结果:
print(result)

输出结果:

grade  student_count  percentage
0     A              2        50.00
1     B              3        75.00
2     C              1        25.00

也可以用链式调用简化代码:

total_students = df['student'].nunique()
result = df.groupby('grade')['student'].nunique()\
           .reset_index(name='student_count')\
           .assign(percentage=lambda x: (x['student_count']/total_students*100).round(2))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 20:25:22