在Python中跨多个列仅保留唯一的重复行

2024-09-28 03:13:58 发布

您现在位置:Python中文网/ 问答频道 /正文

考虑数据文件如下:

>>> 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行不是“唯一”重复项,因为第2行中也出现过一次样式“cup”。但是第3行和第4行是唯一的重复,因为品牌“Indomie”和风格“pack”从未出现在任何其他行中

因此,我如何根据列品牌和样式保留唯一副本,以获得如下预期输出

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

Tags: falsedfstyle风格副本样式packcup
2条回答
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

您可以使用groupby+nunique()根据另一列中的值查看一列中唯一值的数量:

>>> df.groupby('style')['brand'].nunique()
style
cup     2
pack    1
Name: brand, dtype: int64
>>> df.groupby('brand')['style'].nunique()
brand
Indomie    1
Nissin     1
Yum Yum    1
Name: style, dtype: int64

与往常一样,您可以使用.transform('nunique')代替原始形状来实现这一点。现在将其与第一个条件结合起来:

>>> df[df.duplicated(['style', 'brand'], keep=False)
... & df.groupby('style')['brand'].transform('nunique').eq(1)
... & df.groupby('brand')['style'].transform('nunique').eq(1)]
     brand style  rating
3  Indomie  pack    15.0
4  Indomie  pack     5.0

相关问题 更多 >

    热门问题