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

如何使用Pandas按Id分组取最高值并按自定义规则输出?

实现代码

你可以直接基于已创建的初始DataFrame执行以下代码,完全兼容Python 3.10 + Pandas 1.3.4运行环境:

# 1. 将MultiIndex转为普通列方便后续操作
df = df.reset_index()

# 2. 计算每个Id分组的最高Score(对应需求1)
df['group_max'] = df.groupby('Id')['Score'].transform('max')

# 3. 每个分组内部按Score降序排序(对应需求4)
df = df.groupby('Id', group_keys=False).apply(
    lambda x: x.sort_values('Score', ascending=False)
).reset_index(drop=True)

# 4. 所有分组按最高Score降序、最高值相同则按Id升序排序(对应需求2)
df = df.sort_values(['group_max', 'Id'], ascending=[False, True]).reset_index(drop=True)

# 5. 处理Id列仅首行展示,同时新增Highest Score列仅首行展示(对应需求3)
df['Id'] = df['Id'].mask(df['Id'].duplicated(), '')
df['Highest Score'] = df['group_max'].mask(df['group_max'].duplicated(), '')

# 6. 删掉临时辅助列,可选将NaN替换为空字符串优化展示效果
df = df.drop(columns='group_max').fillna('')

# 输出最终结果
print(df)
输出效果参考
IdNameScoreDeptHighest Score
358John Smith1.0WL1.0
John B. Smith1.0AM
Jonathan Smith0.77PP
496John Smith1.0WL1.0
John A. Smithy0.99PP
John Smythe0.97WL
228John Smith0.98WL0.98
433Jon Smithson0.80AM0.8
123Johnny Smith0.65PP0.65
James Smith0.56AM

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 16:54:07