You need to enable JavaScript to run this app. Pandas使用groupby分组聚合时如何为每组添加对应分组行数新列
优惠活动
大模型
产品
解决方案
定价
更多

Pandas使用groupby分组聚合时如何为每组添加对应分组行数新列

方法1:单次groupby使用agg同时聚合(推荐,性能最优)

只做一次分组操作,同时完成均值计算和行数统计,适合大体积数据集:

import pandas as pd
df = pd.read_excel(r'a.xlsx')
df2 = df.groupby(by=["col"], as_index=False).agg(
    # 保留原逻辑:所有数值列计算均值
    **{col: (col, 'mean') for col in df.select_dtypes('number').columns if col != 'col'},
    # 新增列统计分组行数,列名可自定义,这里用group_size
    group_size=('col', 'size')
)

说明:size统计分组内所有行(包含空值行),如果需要统计某列非空行数,将'size'替换为对应的列名和'count'即可

方法2:分组结果合并(逻辑更直观)

如果不想改动原有聚合逻辑,可以单独计算分组行数后和均值结果合并:

import pandas as pd
df = pd.read_excel(r'a.xlsx')
# 原有均值计算逻辑不变
df_mean = df.groupby(by=["col"], as_index=False).mean()
# 单独统计每个分组的行数
df_group_cnt = df.groupby(by=["col"], as_index=False).size().rename(columns={'size': 'group_size'})
# 按分组键合并两个结果
df2 = df_mean.merge(df_group_cnt, on='col')

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.10 10:21:01