【问题标题】:Filter and display all duplicated rows based on multiple columns in Pandas [duplicate]根据 Pandas 中的多列过滤并显示所有重复的行 [重复]
【发布时间】:2020-12-01 03:48:42
【问题描述】:

给定一个数据集如下:

    name     month  year
0    Joe  December  2017
1  James   January  2018
2    Bob     April  2018
3    Joe  December  2017
4   Jack  February  2018
5   Jack     April  2018

我需要根据 Pandas 中的 monthyear 列过滤和显示所有重复的行。

使用下面的代码,我得到:

df = df[df.duplicated(subset = ['month', 'year'])]
df = df.sort_values(by=['name', 'month', 'year'], ascending = False)

输出:

   name     month  year
3   Joe  December  2017
5  Jack     April  2018

但我想要的结果如下:

    name     month  year
0    Joe  December  2017
1    Joe  December  2017
2    Bob     April  2018
3   Jack     April  2018

我怎么能在 Pandas 中做到这一点?

【问题讨论】:

标签: python-3.x pandas dataframe


【解决方案1】:

下面的代码可以通过添加keep = False

df = df[df.duplicated(subset = ['month', 'year'], keep = False)]
df = df.sort_values(by=['name', 'month', 'year'], ascending = False)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-06-13
    • 2018-03-21
    • 2015-12-02
    • 2019-03-01
    • 1970-01-01
    • 2016-07-16
    • 2014-10-16
    • 1970-01-01
    相关资源
    最近更新 更多