如何对pd.DataFrame按id/topic聚合统计学生数与消息数?
解决方案:Pandas按id和topic分组聚合统计
这其实是Pandas里非常常见的分组聚合需求,用groupby配合agg方法就能完美实现你的要求,具体代码如下:
import pandas as pd # 假设你的数据集已经存储在df中 result = df.groupby(['id', 'topic']).agg( num_students=('student', 'nunique'), # 统计每个组的唯一学生数 num_messages=('student', 'count') # 统计每个组的记录条数 ).reset_index() # 输出结果 print(result)
代码解释:
groupby(['id', 'topic']):指定按id和topic这两列进行分组,确保我们统计的是每个id/topic组合下的数据。agg()方法:用来定义多个聚合操作:num_students=('student', 'nunique'):对student列使用nunique()函数,统计组内唯一学生的数量,并将结果列命名为num_students。num_messages=('student', 'count'):对student列使用count()函数,统计组内的总记录条数(这里用任意列做count都可以,因为是统计组的行数),命名为num_messages。
reset_index():将分组后的索引(id和topic)转换为普通列,让结果格式和你预期的完全一致。
运行这段代码后,你会得到和预期完全匹配的输出:
id topic num_students num_messages 0 1 sun 2 2 1 1 moon 1 1 2 2 tree 2 4 3 3 cloud 3 4 4 3 house 1 1
内容的提问来源于stack exchange,提问作者Sheron
相关产品推荐
相关产品推荐

