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

pandas groupby聚合如何按分组求和并提取出现次数最多的字符串

pandas分组聚合实现方案

你可以通过groupby搭配多字段自定义聚合规则实现需求,核心是对Amount做求和、对Location取众数(出现次数最多的值),代码实现如下:

步骤1:导入依赖并构造测试数据

import pandas as pd

# 对应你给出的原始结构化数据
df = pd.DataFrame({
    "Customer ID": [1, 2, 1, 2, 1, 1, 2],
    "Amount": [2500, 3000, 1000, 500, 2500, 500, 500],
    "Location": ["India", "USA", "India", "India", "India", "USA", "USA"]
})

步骤2:执行分组聚合

res = df.groupby("Customer ID", as_index=False).agg(
    # Amount字段直接求和
    Amount=("Amount", "sum"),
    # Location字段取出现次数最多的值,取[0]避免存在多个众数时返回列表
    Location=("Location", lambda x: pd.Series.mode(x)[0])
)

运行结果说明

上述代码运行后得到的结果如下:

Customer IDAmountLocation
16500India
24000USA

你给出的预期结果中两个Amount值存在计算笔误,以上为原始数据的真实计算结果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 15:24:00