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

Pandas按date分组获取对应最高price的store值实现方法

Pandas分组获取最大值对应列值的实现方法

先给出初始数据的代码:

import pandas as pd

data = {'date':['2022-10-01', '2022-10-01', '2022-10-02', '2022-10-02', '2022-10-02'],
'price': [10, 20, 30, 40, 50],
'store': ['A', 'B', 'A', 'C', 'B']
}
df = pd.DataFrame(data)

给你几种靠谱的实现方式:

方法一:通过索引定位最大值行

先分组获取每组price最大值对应的行索引,再用索引筛选出目标行:

# 获取每组price最大值的行索引
max_row_indices = df.groupby('date')['price'].idxmax()
# 根据索引提取结果并重置索引
result = df.loc[max_row_indices].reset_index(drop=True)
print(result)

输出结果:

date  price store
0  2022-10-01     20     B
1  2022-10-02     50     B

方法二:排序后去重

先按date升序、price降序排序,然后保留每组的第一行即可:

result = df.sort_values(by=['date', 'price'], ascending=[True, False]) \
          .drop_duplicates(subset='date') \
          .reset_index(drop=True)

方法三:用transform标记最大值行

通过transform给每行标记是否为该组的price最大值,再筛选标记为True的行:

# 添加辅助列标记是否为组内price最大值
df['is_price_max'] = df.groupby('date')['price'].transform(lambda x: x == x.max())
# 筛选目标行并移除辅助列
result = df[df['is_price_max']].drop(columns='is_price_max').reset_index(drop=True)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 21:20:40