我正在尝试从数据框中删除出现次数少于 100 次的条目。
数据框 data
如下所示:
pid tag
1 23
1 45
1 62
2 24
2 45
3 34
3 25
3 62
现在我像这样计算标 checkout 现的次数:
bytag = data.groupby('tag').aggregate(np.count_nonzero)
但是我不知道如何删除那些计数低的条目......
最佳答案
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
函数(filter的第一个参数)被应用于每个组(子帧),结果包括原始DataFrame中属于评估为True的组的元素。
注意: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
关于Python Pandas : remove entries based on the number of occurrences,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13446480/