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

如何将group_by().apply与自定义聚合函数整合为单个函数

合并聚合函数的解决方案

我需要将两个自定义函数整合为一个,同时保留agr_list的聚合逻辑——该函数负责计算quantity的总和,以及revenue(quantity与price的乘积之和);而gr函数原本是通过groupby和apply调用agr_list完成聚合。最终采用将agr_list嵌套在gr函数内部的方式实现了需求。

原代码

def agr_list(x):
    f = {}
    f['quantity'] = sum(x['quantity'])
    f['revenue'] = sum(x['quantity']*x['price'])
    return pd.Series(f, index=['quantity', 'revenue'])
def gr(df, gr_col):
    return df.groupby(gr_col, as_index=False).apply(agr_list)

整合后的代码

def gr(df, gr_col):

    def agr_list(x):
        f = {}
        f['quantity'] = sum(x['quantity'])
        f['revenue'] = sum(x['quantity']*x['price'])
        return pd.Series(f, index=['quantity', 'revenue'])

    return df.groupby(gr_col, as_index=False).apply(agr_list)

执行结果

name             quantity     revenue
0   Avocaddo         20           3556
1   Got meat!        2            818
2   Pineapple        2            620
3   Pineapple sort2  1            219
4   Dove             1            229
5   Cotico           1            149
6   Orange           6            1014
7   Peanut           7            315
8   Baguette         2            251
9   Kotanyi          1            59

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 16:20:21