当数据框中列值的出现次数小于特定数量时使用 pandas/python 删除行?

Remove rows when the occurrence of a column value in the data frame is less than a certain number using pandas/python?

我有一个这样的数据框:

df
col1    col2
A         1
B         1
C         2
D         3
D         2
B         1
D         5

我看到带有 B 和 D 的 col1 值在数据框中出现了不止一次。

我想保留那些出现次数超过 1 的值,最终数据框将如下所示:

col1     col2
 B         1
 D         3
 D         2
 B         1
 D         5

如何使用 pandas/python 以最有效的方式做到这一点?

使用DataFrame.duplicated with specify column col1 for search dupes with keep=False for return Trues for all dupe rows, last filter by boolean indexing:

df = df[df.duplicated('col1', keep=False)]
print (df)
  col1  col2
1    B     1
3    D     3
4    D     2
5    B     1
6    D     5

如果需要指定阈值,请将 transformsize 一起使用,并按照与第一个解决方案相同的方式进行过滤:

df = df[df.groupby('col1')['col1'].transform('size') > 1]
print (df)
  col1  col2
1    B     1
3    D     3
4    D     2
5    B     1
6    D     5

value_counts and map 的替代解决方案:

df = df[df['col1'].map(df['col1'].value_counts()) > 1]

如果性能不重要使用DataFrameGroupBy.filter:

df = df.groupby('col1').filter(lambda x: len(x) > 1)

您可以在数据框上使用 duplicated setting keep=False, which will return True for all duplicate values in col1, and then simply use boolean indexation

df[df.col1.duplicated(keep=False)]

   col1  col2
1    B     1
3    D     3
4    D     2
5    B     1
6    D     5

更新

要保持​​ col1 出现超过 thr 次的值,请使用:

thr = 2
df[df.col1.duplicated(keep=False).groupby(df.col1).transform('sum').gt(thr)]

   col1  col2
3    D     3
4    D     2
6    D     5