首页 > 解决方案 > 在 Python Pandas 的多列中只保留唯一的重复行

问题描述

考虑如下数据帧:

>>> df
        brand  style  rating
    0  Yum Yum   cup     4.0
    1  Yum Yum   cup     4.0
    2  Nissin    cup     3.5
    3  Indomie  pack    15.0
    4  Indomie  pack     5.0

根据列保持重复非常容易:品牌风格使用:

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

输出:

>>> df = df[df.duplicated(['brand', 'style'], keep=False)]
>>> df
        brand  style  rating
    0  Yum Yum   cup     4.0
    1  Yum Yum   cup     4.0
    3  Indomie  pack    15.0
    4  Indomie  pack     5.0

但我只想保留的行是第 3 行和第 4 行。原因如下:

用于识别重复项的子集列是品牌风格。第 0 行和第 1 行不是“唯一”重复项,因为样式“cup”在第 2 行中也出现过一次。但是第 3 行和第 4 行是唯一的重复项,因为“Indomie”品牌和“pack”风格都没有出现在任何其他行中。

因此,如何根据列品牌和样式保留唯一重复项,以获得如下预期输出?

>>> df
        brand  style  rating
    3  Indomie  pack    15.0
    4  Indomie  pack     5.0

标签: pythonpandas

解决方案


df = df[~df.duplicated()] # Add this line before
df[df.duplicated(['brand', 'style'], keep=False)]
    brand   style   rating
3   Indomie pack    15.0
4   Indomie pack    5.0

推荐阅读