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

如何对pandas dataframe分组后同时应用涉及多列的多个聚合函数

解决方案

你可以通过以下两种方法实现需求:

方法1:先计算差值列再聚合(性能更优)

提前新增临时列存储每行max减score的结果,再分组对不同列指定不同聚合规则即可:

import pandas as pd

# 构造测试数据
df = pd.DataFrame({
    'id': ['s1', 's1', 's2', 's2', 's3', 's3'],
    'cat': ['A', 'B', 'C', 'D', 'E', 'F'],
    'date': ['12/06', '12/06', '11/04', '11/04', '08/02', '08/02'],
    'max': [9, 10, 13, 28, 16, 6],
    'score': [5.4, 5.4, 4.2, 10, 5.4, 5.4]
})

# 新增差值列
df['max_minus_score'] = df['max'] - df['score']

# 分组聚合
res = df.groupby('id', as_index=False).agg(
    cat = ('cat', 'first'),
    date = ('date', 'first'),
    mean_max_minus_score = ('max_minus_score', 'mean')
).rename(columns={'mean_max_minus_score': 'mean(max-score)'})

方法2:使用apply直接处理分组

不需要提前新增列,直接对每个分组做自定义计算:

def process_group(group):
    return pd.Series({
        'cat': group['cat'].iloc[0],
        'date': group['date'].iloc[0],
        'mean(max-score)': (group['max'] - group['score']).mean()
    })

res = df.groupby('id', as_index=False).apply(process_group)

两种方法得到的结果都和你预期的输出完全一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 17:54:03