首页 > 解决方案 > 具有复杂标准的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 帖子,但还没有找到这种情况。任何帮助将不胜感激。

标签: pythonpandasdataframe

解决方案


我认为我们可以用一个布尔值来做到这一点。使用.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

推荐阅读