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

如何用Pandas按year分组获取dollar_amount最大值及对应item_code

解决方案

要实现你想要的按year分组,同时获取年度dollar_amount最大值及其对应的item_code,这里有两种简单好用的方法:

方法1:通过idxmax定位最大值行

这种思路是先找到每个年份组里金额最大的那一行的索引,再直接提取整行数据,能完整保留对应的item_code:

import pandas as pd

# 初始化你的数据
d = {'item_code': ['Item1', 'Item2', 'Item3', 'Item1', 'Item2', 'Item2', 'Item2', 'Item1', 'Item3'], 
     'dollar_amount': ['200.25', '350.00', '120.00', '400.50', '1231.25', '700.00', '350.00', '200.25', '2340.00'], 
     'year': ['2010','2010','2010','2011','2011','2012','2012','2012','2012']}
df = pd.DataFrame(data=d)

# 先把金额列转成浮点型,方便计算
df['dollar_amount'] = df['dollar_amount'].astype(float)

# 找到每个年份组中金额最大的行的索引
max_row_indices = df.groupby('year')['dollar_amount'].idxmax()

# 根据索引提取对应行,再重置索引整理格式
result = df.loc[max_row_indices, ['year', 'dollar_amount', 'item_code']].reset_index(drop=True)

print(result)

运行后输出:

year  dollar_amount item_code
0  2010         350.00     Item2
1  2011        1231.25     Item2
2  2012        2340.00     Item3

方法2:排序后去重

另一种思路是先按年份和金额降序排序,然后每个年份只保留第一行(也就是金额最大的那一行):

# 转换金额列后,先排序再去重
result = df.sort_values(by=['year', 'dollar_amount'], ascending=[True, False]) \
           .drop_duplicates(subset='year', keep='first') \
           .reset_index(drop=True)[['year', 'dollar_amount', 'item_code']]

print(result)

这个方法的输出和方法1完全一致,操作起来更简洁,适合数据量不大的场景。

小提示

如果同一个年份里有多个行的dollar_amount都是最大值,上面两种方法都会保留第一个出现的行。要是你需要把所有对应最大值的item_code都收集起来,可以用groupby结合apply的方式,比如:

result = df.groupby('year').apply(
    lambda x: x[x['dollar_amount'] == x['dollar_amount'].max()]
).reset_index(drop=True)

这样就能得到所有年度最大值对应的行啦。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 07:21:09