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

标签 python pandas

如您所知,.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

在此先感谢您的帮助和支持!

最佳答案

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

关于python - 如何标记 pandas DataFrame 中的最后一个重复元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55608298/

相关文章:

python - 读取和写入数据包 python-scapy

Pandas,使用用于绘图的引导置信区间计算许多方法

python - pandas - 返回指数值列

pandas - 计算重复集并添加为新列

python - 将具有分层列索引的宽格式 pandas DataFrame 转换为整齐格式

Python Bottle - "redirect"和 "return template"之间的区别

python - 主页登录表单 Django

python - 对非时间数据进行上采样

python - 如何将一列时间戳转换为日期时间?

python - 循环 numpy 数组索引