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

Pandas分组后如何按score最大值匹配对应最小Key值?

如何在分组后获取对应最大score的最小Key值?

我来帮你解决这个问题!先明确你的核心需求:按Device和time分组,先拿到每组的最大score,再在该组所有等于这个最大score的行中,找到最小的Key值。你的两次尝试都没命中需求,下面给你两个可行的解决方案:

测试数据回顾

先把你的测试数据列出来方便参考:

Device     time        Key  score
Computers  2018-01-01  14.0  4.0
Computers  2018-01-01  11.0  4.0
Computers  2018-01-01  16.0  0.0

方法一:先筛选再分组(高效直观)

思路是先标记出每组中等于最大score的行,再在这些行里取最小的Key:

import pandas as pd

# 假设你的原始数据存在df中
df = pd.DataFrame({
    'Device': ['Computers', 'Computers', 'Computers'],
    'time': ['2018-01-01', '2018-01-01', '2018-01-01'],
    'Key': [14.0, 11.0, 16.0],
    'score': [4.0, 4.0, 0.0]
})

# 步骤1:计算每个[Device, time]组的最大score,添加到原表中
df['group_max_score'] = df.groupby(['Device', 'time'])['score'].transform('max')

# 步骤2:筛选出score等于组内最大值的行
filtered_rows = df[df['score'] == df['group_max_score']]

# 步骤3:按分组聚合,保留score最大值,取Key的最小值
result = filtered_rows.groupby(['Device', 'time']).agg(
    score=('score', 'first'),  # 筛选后所有score都是组内最大值,取first即可
    Key=('Key', 'min')
).reset_index()

print(result)

运行后就能得到你想要的输出:

Device        time  score   Key
0  Computers  2018-01-01    4.0  11.0

方法二:用groupby的apply自定义处理

如果喜欢更灵活的方式,可以给每个分组写一个自定义处理函数:

def process_group(group):
    # 拿到当前组的最大score
    max_score = group['score'].max()
    # 在当前组中筛选出score等于max_score的行,取Key的最小值
    min_key = group[group['score'] == max_score]['Key'].min()
    # 返回需要的结果
    return pd.Series({'score': max_score, 'Key': min_key})

# 应用到分组上
result = df.groupby(['Device', 'time']).apply(process_group).reset_index()

print(result)

这个方法和方法一结果一致,适合需要更复杂分组逻辑的场景。

为什么你的之前尝试不对?

  • 第一次尝试只聚合了score的最大值,完全丢失了Key的关联信息,自然拿不到对应的值;
  • 第二次尝试直接对score和Key都取最大值,这会把组内最大的Key(14.0)和最大的score(4.0)拼在一起,但这两个值并不是来自同一行的关联关系,不符合你的需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 06:30:14