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

Pandas分组获取各州Top5欺诈分后,如何添加原数据的保单号与索赔成本列?

解决按州获取Top5欺诈分并保留完整列的问题

方法一:使用groupby + apply + nlargest

直接对每个州的分组DataFrame调用nlargest,保留所有需要的列:

# 按州分组,每组取欺诈分前5的行
final = fraud_score.groupby('state').apply(lambda x: x.nlargest(5, 'fraud_score')).reset_index(drop=True)

处理后final会包含policy_num、state、claim_cost和fraud_score所有列,每个州仅保留欺诈分最高的5条记录。

方法二:使用rank筛选

先给每个州内的记录按欺诈分排名,再筛选排名前5的条目:

# 给每个州内的欺诈分降序排名(相同分数按出现顺序区分)
fraud_score['fraud_rank'] = fraud_score.groupby('state')['fraud_score'].rank(ascending=False, method='first')

# 筛选排名前5的记录,删除临时排名列
final = fraud_score[fraud_score['fraud_rank'] <= 5].drop('fraud_rank', axis=1)

# 按州和欺诈分降序排序(可选,优化结果展示)
final = final.sort_values(['state', 'fraud_score'], ascending=[True, False])

原代码丢失列的原因

你之前的代码top5.groupby("state")["fraud_score"].nlargest(5)仅针对fraud_score列操作,返回结果只有该列和分组索引,因此丢失了policy_num和claim_cost。上面两种方法都是对整个分组的DataFrame处理,所以能保留所有需要的列。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 02:38:31