从pandas中删除非重复行

时间:2017-08-05 22:43:47

标签: python pandas

这很简单,但我无法理解它。假设对于以下数据框,我想只保留y列中具有重复值的行:

>>> df
   x  y
    x   y
0   1   1
1   2   2
2   3   2
3   4   3
4   5   3
5   6   3
6   7   5
7   8   2

所需的输出如下:

>>> df
    x   y
1   2   2
2   3   2
3   4   3
4   5   3
5   6   3
7   8   2

我试过了:

df[~df.duplicated('y')]

但我明白了:

    x   y
0   1   1
1   2   2
3   4   3
6   7   5

1 个答案:

答案 0 :(得分:4)

文档:https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.duplicated.html

  

保持:{'first','last',False},默认为'first'

     
      
  • 首先:马克   除第一次出现外,重复为True。

  •   
  • 最后:马克   除最后一次出现外,重复为True。

  •   
  • 错误:全部标记   重复为True。

  •   

您正在寻找的意思:

df[df.duplicated('y',keep=False)]

输出:

    x   y
1   2   2
2   3   2
3   4   3
4   5   3
5   6   3
7   8   2
相关问题