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

4

如您所知,有一个名为.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

感谢您的帮助和支持!


你目前尝试了什么?你查阅了duplicated()的文档吗? - Jondiedoop
2个回答

2
使用Series.duplicatedDataFrame.duplicated指定列和参数keep='last', 然后将反转的掩码转换为整数进行True/False1/0的映射,或者使用numpy.where:「最初的回答」。
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

@SabiriS. - 不用谢,特别感谢您提供这么好的数据样本。 - jezrael
请问您能帮我解决这个问题吗?您的答案帮助我更好地理解了。链接为:https://stackoverflow.com/questions/55596750/how-to-detect-change-in-last-2-months-starting-from-specific-row-in-pandas-dataf - Soufiane Sabiri

0

也可以用以下方式完成(不使用 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)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接