python - 在 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
解决方案
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
推荐阅读
- reactjs - 如何从传递给 Redux Thunk 的 Redux Action 访问异步函数?
- java - android在触摸和移动时获取按钮文本
- c# - C# 数据从文件中提取到字节数组中
- vue.js - VueJS 在 laravel 中无法正常工作
- javascript - 如何在php中对表格进行排序并在发布PHP后保持表格排序
- php - Laravel 表通过枢轴引用自身
- javascript - Ajax 不发送电子邮件,但状态为 200
- r - 手指上的细菌。MASS::glmmPQL 中具有随机斜率但没有截距的交叉随机效应的语法
- multithreading - 如何在 web api 2 中将多线程与实体框架一起使用
- jquery - Mozilla FireFox 中的警报图标未关闭