考虑数据文件如下:
>>> 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
您可以使用groupby+
nunique()
根据另一列中的值查看一列中唯一值的数量:与往常一样,您可以使用
.transform('nunique')
代替原始形状来实现这一点。现在将其与第一个条件结合起来:相关问题 更多 >
编程相关推荐