python - 根据两列的值删除数据框 pandas 中的重复项

标签 python pandas dataframe duplicates

我有一个包含某些商品的客户数据框,如下所示:

Customer ID     Item
     1         Banana
     1         Apple
     2         Orange
     3         Grape
     4         Banana
     4         Apple
     5         Orange
     5         Grape
     6         Orange

我愿意做的是删除具有相同项目的所有重复客户,因此结果应如下所示:

Customer ID     Item
     1         Banana
     1         Apple
     2         Orange
     3         Grape
     5         Orange
     5         Grape

由于客户 4 拥有与客户 1 相同的商品。客户 6 也拥有 2 的商品。

预先感谢您的帮助!

最佳答案

不确定这是不是你的意思。但是,如果您指的是基于商品的重复项,则可以将每个客户的商品收集为卡住集(如果唯一)或元组(如果不唯一),然后应用drop_duplicates;稍后根据客户 ID 对原始数据框进行过滤。

df[df["Customer ID"].isin(df.groupby("Customer ID").Item.apply(frozenset).drop_duplicates().index)]

enter image description here

或者,如果项目不是唯一的并且顺序并不重要:

df[df["Customer ID"].isin(df.groupby("Customer ID")
                            .Item.apply(lambda x: tuple(sorted(x)))
                            .drop_duplicates().index)]

关于python - 根据两列的值删除数据框 pandas 中的重复项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43096288/

相关文章:

Python numpy 数组操作

python - 在 python 中将 timedelta 转换为 int 非常慢

python - 如何找到相关矩阵中的高值?

python - 如何创建具有互斥参数的 Python 函数?

python - 似乎无法打印任何内容

python - 使用 PYTHON 将 3 维 DataFrame 转换为 3 维数组时出现问题

python - 根据自定义条件过滤 csv 中的行

python - 在 Pandas 中读取带有 NaN 的整数时如何保留 dtype int

python - if/else 与 Python Pandas Dataframe

python - Pandas:合并数据帧并仅保留与合并的唯一对关联的最小值