如何标记DataFram中的最后一个重复元素

2024-09-30 05:22:09 发布

您现在位置:Python中文网/ 问答频道 /正文

正如您所知,有一种方法.duplicated来查找列中的重复项,但我需要的是最后一个重复的元素,它知道我的数据是按日期排序的。你知道吗

以下是列Policy_id的预期结果Last_dup

Id  Policy_id   Start_Date  Last_dup
0   b123        2019/02/24  0
1   b123        2019/03/24  0
2   b123        2019/04/24  1
3   c123        2018/09/01  0
4   c123        2018/10/01  1
5   d123        2017/02/24  0
6   d123        2017/03/24  1

感谢您的帮助和支持!你知道吗


Tags: 数据方法id元素date排序policystart
2条回答

也可以用下面提到的方法完成(不使用Series.duplicated):

dictionary = df[['Id','Policy_id']].set_index('Policy_id').to_dict()['Id']
#here the dictionary values contains the most recent Id's
df['Last_dup'] = df.Id.apply(lambda x: 1 if x in list(dictionary.values()) else 0)

使用^{}^{}指定列和参数keep='last',然后将True/False1/0映射的反向掩码转换为整数,或使用^{}

df['Last_dup1'] = (~df['Policy_id'].duplicated(keep='last')).astype(int)
df['Last_dup1'] = np.where(df['Policy_id'].duplicated(keep='last'), 0, 1)

或:

df['Last_dup1'] = (~df.duplicated(subset=['Policy_id'], keep='last')).astype(int)
df['Last_dup1'] = np.where(df.duplicated(subset=['Policy_id'], keep='last'), 0, 1)

print (df)
   Id Policy_id  Start_Date  Last_dup  Last_dup1
0   0      b123  2019/02/24         0          0
1   1      b123  2019/03/24         0          0
2   2      b123  2019/04/24         1          1
3   3      c123  2018/09/01         0          0
4   4      c123  2018/10/01         1          1
5   5      d123  2017/02/24         0          0
6   6      d123  2017/03/24         1          1

相关问题 更多 >

    热门问题