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 ID | Amount | Location |
|---|---|---|
| 1 | 6500 | India |
| 2 | 4000 | USA |
你给出的预期结果中两个Amount值存在计算笔误,以上为原始数据的真实计算结果。
内容的提问来源于stack exchange,提问作者Musaib Jan
相关产品推荐
相关产品推荐

