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

Pandas使用sort_values查询分组最高价时同价数据合并方法问询

Pandas按多字段分组取最高价并拼接所有对应Location的实现方案

需求:按ID、Item两列分组,查询每组最高价格,若组内存在多条最高价记录,将所有对应Location用逗号拼接输出。

方法1:单步groupby聚合实现(无需新增临时列)

import pandas as pd

# 测试用例(新增同组同最高价记录验证效果)
applesdf = {'ID': [1,1,1],
        'Item': ['Apple','Apple','Apple'],
        'Price': [2,1,2],
        'Location':[1001,1002,1003]
        }
df = pd.DataFrame(applesdf, columns = ['ID','Item','Price','Location'])

# 核心实现代码
applesmax = df.groupby(['ID', 'Item'], as_index=False).agg(
    Price=('Price', 'max'),
    Location=('Location', lambda x: ','.join(map(str, x[df.loc[x.index, 'Price'] == x.max()])))
).reset_index(drop=True)

逻辑说明:

  • 按ID、Item分组后直接做自定义聚合
  • Price字段直接取分组最大值
  • Location字段筛选出组内价格等于最高价的所有值,拼接为字符串
    如果需要返回列表格式的Location,把','.join(map(str, ...))替换为list(...)即可。

方法2:先标记最高价行再聚合(可读性更高)

# 给每行打标:是否属于所属ID+Item组的最高价行
df['is_max'] = df['Price'] == df.groupby(['ID', 'Item'])['Price'].transform('max')
# 筛选最高价行后分组拼接Location
applesmax = df[df['is_max']].groupby(['ID', 'Item'], as_index=False).agg(
    Price=('Price', 'first'),
    Location=('Location', lambda x: ','.join(map(str, x)))
).reset_index(drop=True)

逻辑说明:先用transform将每组最高价广播到组内所有行,筛选出所有符合条件的最高价行后再做聚合,逻辑更直观,适合新手理解。

效果验证

上述测试用例运行后输出结果如下:

IDItemPriceLocation
1Apple21001,1003

内容的提问来源于stack exchange,提问作者i.d.s.chicago

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 18:36:03