Pandas按Position分组获取Grandtotal最大值并保留Player列
Pandas分组获取每组最大值并保留对应player字段
你现在的需求是按position字段分组,拿到每组grandtotal的最大值,同时把对应的player也保留在结果里对吧?之前的代码只拿到了分组后的最大值,没带上玩家名称,我给你两个实用的解决方案:
方法一:用idxmax()定位最大值行(推荐高效版)
这个方法通过找到每组最大值的行索引,直接提取对应数据,效率很高,适合大数据量场景:
import pandas as pd # 你的示例DataFrame result = pd.DataFrame([ {'position': 'Top', 'grandtotal': 36.72, 'player': 'Joe'}, {'position': 'Top', 'grandtotal': 101.18, 'player': 'Bill'}, {'position': 'Middle', 'grandtotal': 33.32, 'player': 'Jim'}, {'position': 'Middle', 'grandtotal': 72.62, 'player': 'Him'}, {'position': 'Bottom', 'grandtotal': 42.61, 'player': 'Tim'}, {'position': 'Bottom', 'grandtotal': 83.98, 'player': 'Slim'}, ]) # 找到每组grandtotal最大值对应的行索引 max_row_indices = result.groupby('position')['grandtotal'].idxmax() # 根据索引提取完整行数据,重置索引让结果更整洁 playerframe = result.loc[max_row_indices].reset_index(drop=True)
运行后playerframe就是你要的结果,完整包含position、player和对应最大的grandtotal。
方法二:排序后去重(直观易懂版)
如果觉得索引操作有点绕,也可以用排序+去重的思路,逻辑更直观:
# 先按position分组,再按grandtotal从高到低排序 sorted_df = result.sort_values( by=['position', 'grandtotal'], ascending=[True, False] ) # 保留每个position的第一行(也就是最大值那行) playerframe = sorted_df.drop_duplicates(subset='position').reset_index(drop=True)
这个方法先把每组里得分最高的行排到最前面,再去掉重复的position条目,留下的就是每组的最高得分玩家数据。
最终结果示例
不管用哪种方法,你都会得到如下结果:
position grandtotal player 0 Bottom 83.98 Slim 1 Middle 72.62 Him 2 Top 101.18 Bill
内容的提问来源于stack exchange,提问作者Sean
相关产品推荐
相关产品推荐

