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

如何使用Pandas找出各城市中得分最高的单一候选人(男性/女性)

解决每个城市得分最高候选人的问题

我明白你要的是每个城市里得分最高的单个候选人(不管性别),你之前的代码是按City+Gender分组,所以才会返回分性别的最高分。下面给你几个简单有效的解决方案:

方法1:使用groupby+idxmax提取最高分对应行

这是最直接的方法,先找到每个城市得分最高的行索引,再提取完整信息:

import pandas as pd
df = pd.DataFrame({
    "City":["Delhi","Delhi","Mumbai","Mumbai","Lahore","Lahore"], 
    "Points":[90.1,90.3,94.1,95,89,90.5], 
    "Gender":["Male","Female","Female","Male","Female","Male"]
})

# 获取每个城市Points最大值的行索引
max_row_indices = df.groupby("City")["Points"].idxmax()
# 提取对应行的完整数据
top_candidates = df.loc[max_row_indices]
print(top_candidates)

运行后输出:

City  Points  Gender
1   Delhi    90.3  Female
3  Mumbai    95.0    Male
5   Lahore    90.5    Male

方法2:排序后去重保留最高分

先按城市分组内的得分降序排序,再保留每个城市的第一条记录:

# 按城市升序、得分降序排序
sorted_df = df.sort_values(["City", "Points"], ascending=[True, False])
# 去重,只保留每个城市的第一行(得分最高的)
top_candidates = sorted_df.drop_duplicates(subset="City", keep="first")
print(top_candidates)

这个方法的好处是如果需要同时看每个城市的得分排名,排序后的DataFrame也能直接复用。

方法3:用transform标记最高分后筛选

通过广播每个城市的最高分,标记出符合条件的行:

# 添加一列标记是否为所在城市的最高分
df["is_top_candidate"] = df["Points"] == df.groupby("City")["Points"].transform("max")
# 筛选出标记为True的行,再去掉辅助列
top_candidates = df[df["is_top_candidate"]].drop(columns="is_top_candidate")
print(top_candidates)

这种方法适合需要保留原DataFrame结构,同时标记出最高分候选人的场景。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.28 08:52:28