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

Pandas按三列分组求和后如何保留其余列?

解决Pandas分组聚合后保留额外列的问题

先看你的场景:你有这样的原始DataFrame:

offer_id affiliate_id affiliate_source affiliate_sub5 advertiser_id Payout_cent Revenue_cents
428572 1327 14331605 14331605 291 50 30
428572 1327 1465 1465 291 50 30
428572 1327 1336 1336 291 50 30
428572 1327 14331605 14331605 291 50 30
428572 1327 14331605 14331605 291 50 30

你执行了分组求和操作:

df1.groupby(['offer_id', 'affiliate_id', 'affiliate_source'])[["Payout_cent", "Revenue_cents"]].sum()

但结果里只保留了聚合的金额列,想要把advertiser_id和affiliate_sub5也保留下来,其实分两种情况处理就好:


情况1:分组内的额外列值完全一致(你的例子就是这种)

观察你的数据,同一个offer_id+affiliate_id+affiliate_source分组下,advertiser_id都是291,affiliate_sub5和affiliate_source值也完全相同,这种情况有两种简单的处理方式:

方式1:把额外列加入分组键

既然这些列在组内值都一样,把它们加到groupby的分组列表里,聚合后自然会保留这些列,最后用reset_index()把索引转成列:

result = df1.groupby(
    ['offer_id', 'affiliate_id', 'affiliate_source', 'advertiser_id', 'affiliate_sub5']
)[["Payout_cent", "Revenue_cents"]].sum().reset_index()

方式2:用agg方法指定不同列的操作

这种方式更灵活,你可以明确指定哪些列要求和,哪些列要保留(因为组内值一致,取第一个/最后一个都可以):

result = df1.groupby(['offer_id', 'affiliate_id', 'affiliate_source']).agg(
    Payout_cent=('Payout_cent', 'sum'),
    Revenue_cents=('Revenue_cents', 'sum'),
    advertiser_id=('advertiser_id', 'first'),  # 用'last'/'max'也没问题,组内值相同
    affiliate_sub5=('affiliate_sub5', 'first')
).reset_index()

情况2:分组内的额外列有不同值

如果你的数据里,同一个分组下advertiser_id或affiliate_sub5有不同的值,那你需要先确定怎么处理这些值——比如取最大值、平均值,或者拼接所有值,然后在agg里指定对应的操作即可。举个例子,如果想把affiliate_sub5的所有值拼接起来:

result = df1.groupby(['offer_id', 'affiliate_id', 'affiliate_source']).agg(
    Payout_cent=('Payout_cent', 'sum'),
    Revenue_cents=('Revenue_cents', 'sum'),
    advertiser_id=('advertiser_id', 'max'),  # 取组内最大的advertiser_id
    affiliate_sub5=('affiliate_sub5', lambda x: ','.join(map(str, x)))  # 拼接所有值
).reset_index()

这样处理后,你就能得到包含所有需要列的聚合结果啦~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 07:42:24