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

在R中基于多条件处理重复ethnicity数据,分配唯一用户类别

多重复族群数据的用户唯一类别分配问题

问题说明

我手里有一批带重复族群(ethnicity)信息的用户数据,每条记录包含用户ID(person)、族群类别(ethnicity)、该类别的计数(ethnicity_n)、分配日期(ethnicity_date)。需要给每个用户分配唯一的族群类别,规则是:

  1. 优先选ethnicity_n(计数)最高的类别;
  2. 要是多个类别计数一样,就选ethnicity_date(分配日期)最新的那个。

我已经按日期降序排了数据,但试了好几种筛选每组首行的代码,结果都不对。下面是相关数据和代码:


原始数据集

personethnicityethnicity_nethnicity_date
1亚洲人32023-05-10
1欧洲人32023-06-15
2非洲人52022-11-01
2美洲人22023-01-20
3大洋洲人42023-03-05
3亚洲人42023-02-28

中间表生成代码(已完成排序)

import pandas as pd

# 读取原始数据
df = pd.read_csv('ethnicity_data.csv')

# 按用户分组,先按计数降序、再按日期降序排序
df_sorted = df.sort_values(
    by=['person', 'ethnicity_n', 'ethnicity_date'],
    ascending=[True, False, False]
)

尝试过的筛选代码(结果不符合预期)

# 尝试1:分组取首行
df_result = df_sorted.groupby('person').first().reset_index()

# 尝试2:去重保留首行
df_result = df_sorted.drop_duplicates(subset='person')

期望的最终输出表

personethnicityethnicity_nethnicity_date
1欧洲人32023-06-15
2非洲人52022-11-01
3大洋洲人42023-03-05

正确解决方案

方法1:排序后去重(最简洁)

确保排序逻辑完全匹配规则后,用drop_duplicates保留每组第一行即可,注意要加keep='first'(默认就是,但写出来更清晰):

# 重新确认排序规则(必须先按person升序,再按ethnicity_n降序,最后ethnicity_date降序)
df_sorted = df.sort_values(
    by=['person', 'ethnicity_n', 'ethnicity_date'],
    ascending=[True, False, False]
)

# 按person去重,保留排序后的第一行
df_final = df_sorted.drop_duplicates(subset='person', keep='first').reset_index(drop=True)

方法2:分组自定义聚合(更稳妥)

如果排序后去重还是有问题,可以直接在分组里写逻辑筛选符合条件的行:

def pick_right_ethnicity(group):
    # 先筛出计数最大的所有行
    max_count_rows = group[group['ethnicity_n'] == group['ethnicity_n'].max()]
    # 再从这些行里挑日期最新的
    return max_count_rows[max_count_rows['ethnicity_date'] == max_count_rows['ethnicity_date'].max()].iloc[0]

# 分组应用函数,得到最终结果
df_final = df.groupby('person').apply(pick_right_ethnicity).reset_index(drop=True)

之前出错的可能原因

  • 排序时没同时按ethnicity_n降序和ethnicity_date降序,只排了日期,导致计数高的行没在组内最前面;
  • 部分Pandas版本中groupby().first()会按原数据的顺序取行,而不是排序后的顺序,这时候用drop_duplicates更可靠。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 07:35:21