Python Pandas:根据出现次数删除条目

时间:2012-11-19 01:20:07

标签: python numpy python-2.7 pandas

我试图从数据框中删除少于100次的条目。 数据框data如下所示:

pid   tag
1     23    
1     45
1     62
2     24
2     45
3     34
3     25
3     62

现在我计算这样的标签出现次数:

bytag = data.groupby('tag').aggregate(np.count_nonzero)

但是我无法弄清楚如何删除那些计数较低的条目......

4 个答案:

答案 0 :(得分:25)

0.12中的新功能,groupby对象具有filter方法,允许您执行以下类型的操作:

In [11]: g = data.groupby('tag')

In [12]: g.filter(lambda x: len(x) > 1)  # pandas 0.13.1
Out[12]:
   pid  tag
1    1   45
2    1   62
4    2   45
7    3   62

函数(过滤器的第一个参数)应用于每个组(子帧),结果包括属于评估为True的组的原始DataFrame的元素。

注意:in 0.12 the ordering is different than in the original DataFrame,这已在0.13 +中修复:

In [21]: g.filter(lambda x: len(x) > 1)  # pandas 0.12
Out[21]: 
   pid  tag
1    1   45
4    2   45
2    1   62
7    3   62

答案 1 :(得分:23)

编辑:感谢@WesMcKinney以更直接的方式展示:

data[data.groupby('tag').pid.transform(len) > 1]

import pandas
import numpy as np
data = pandas.DataFrame(
    {'pid' : [1,1,1,2,2,3,3,3],
     'tag' : [23,45,62,24,45,34,25,62],
     })

bytag = data.groupby('tag').aggregate(np.count_nonzero)
tags = bytag[bytag.pid >= 2].index
print(data[data['tag'].isin(tags)])

产量

   pid  tag
1    1   45
2    1   62
4    2   45
7    3   62

答案 2 :(得分:2)

df = pd.DataFrame([(1, 2), (1, 3), (1, 4), (2, 1),(2,2,)], columns=['col1', 'col2'])

In [36]: df
Out[36]: 
   col1  col2
0     1     2
1     1     3
2     1     4
3     2     1
4     2     2

gp = df.groupby('col1').aggregate(np.count_nonzero)

In [38]: gp
Out[38]: 
      col2
col1      
1        3
2        2

让我们得到计数> 2

tf = gp[gp.col2 > 2].reset_index()
df[df.col1 == tf.col1]

Out[41]: 
   col1  col2
0     1     2
1     1     3
2     1     4

答案 3 :(得分:2)

以下是此处发布的几个解决方案的一些运行时间,以及一个不是(使用value_counts())的解决方案比其他解决方案快得多:

创建数据:

import pandas as pd
import numpy as np

# Generate some 'users'
np.random.seed(42)
df = pd.DataFrame({'uid': np.random.randint(0, 500, 500)})

# Prove that some entries are 1
print "{:,} users only occur once in dataset".format(sum(df.uid.value_counts() == 1))

输出:

171 users only occur once in dataset

使用一个条目删除用户的几种不同方法。这些是在Jupyter笔记本中的不同单元格中运行的:

%%timeit
df.groupby(by='uid').filter(lambda x: len(x) > 1)

%%timeit
df[df.groupby('uid').uid.transform(len) > 1]

%%timeit
vc = df.uid.value_counts()
df[df.uid.isin(vc.index[vc.values > 1])].uid.value_counts()

这些产生了以下输出:

10 loops, best of 3: 46.2 ms per loop
10 loops, best of 3: 30.1 ms per loop
1000 loops, best of 3: 1.27 ms per loop