python - 具有复杂标准的python pandas重复数据删除
问题描述
我在下面有一个数据框:
import pandas as pd
d = {'id': [1, 2, 3, 4, 4, 6, 1, 8, 9], 'cluster': [7, 2, 3, 3, 3, 6, 7, 8, 8]}
df = pd.DataFrame(data=d)
df = df.sort_values('cluster')
如果存在相同的集群但 id 不同,我想保留所有行,并保留该集群中的每一行,即使它是相同的 id,因为在该集群中至少有一次不同的 id。我一直用来实现这一点的代码如下,但是,唯一的问题是它为我正在寻找的内容丢弃了太多行。
df = (df.assign(counts=df.count(axis=1))
.sort_values(['id', 'counts'])
.drop_duplicates(['id','cluster'], keep='last')
.drop('counts', axis=1))
我期望上面的代码不会执行的输出数据帧将删除数据帧索引 1、5、0 和 6 处的行,但保留数据帧索引 2、3、4、7 和 8。基本上导致下面的代码产生:
df = df.loc[[2, 3, 4, 7, 8]]
我查看了许多关于堆栈溢出的重复数据删除 pandas 帖子,但还没有找到这种情况。任何帮助将不胜感激。
解决方案
我认为我们可以用一个布尔值来做到这一点。使用.groupby().nunique()
con1 = df.groupby('cluster')['id'].nunique() > 1
#of these we only want the True indexes.
cluster
2 False
3 True
6 False
7 False
8 True
df.loc[(df['cluster'].isin(con1[con1].index))]
id cluster
2 3 3
3 4 3
4 4 3
7 8 8
8 9 8
推荐阅读
- google-app-engine - 强制 Google App Engine IP 刷新
- vba - 在 VBA 中访问 O365 组日历文件夹
- javascript - 如何使用 JavaScript 将输入从文本框获取到变量,然后打印变量的值?
- javascript - 在 Mocha 和 Chai 中测试 Promise
- chart.js - 使用 chart.js 和 moment.js 进行奇怪的时间格式化
- highcharts - 高图中样条系列的轮廓或边框
- linq - 如何将带有 switch 语句的 foreach 循环转换为 LINQ
- javascript - 用html写入另一个页面
- tfs - 在 visualstudio.com 上为 TFS 创建新管道
- python - 如果存在某个值,则解析 Json