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

如何对DataFrame按ID去重,按优先级规则保留最高等级的Class值

DataFrame按ID去重并保留最高优先级Class的实现方法

核心思路

  • 为Class字段配置优先级权重,优先级越高对应数值越大
  • 按ID分组后筛选出每组优先级最高的记录即可

可运行代码示例

import pandas as pd

# 1. 构造示例数据集
df = pd.DataFrame({
    'Id.': [111, 111, 111, 222, 333, 333],
    'Class': ['Metro', 'Urban', 'Rural', 'Rural', 'Urban', 'Metro']
})

# 2. 定义Class优先级映射:Metro > Urban > Rural
priority_map = {'Metro': 3, 'Urban': 2, 'Rural': 1}
df['priority'] = df['Class'].map(priority_map)

# 3. 按Id.分组取优先级最高的记录
# 方法1:排序后去重
result = df.sort_values('priority', ascending=False).drop_duplicates('Id.').sort_values('Id.').drop('priority', axis=1)

# 方法2:groupby + idxmax(代码更简洁)
# result = df.loc[df.groupby('Id.')['priority'].idxmax()].drop('priority', axis=1)

print(result)

输出结果

Id.  Class
0  111  Metro
3  222  Rural
5  333  Metro

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 11:15:04