Python Pandas:根据出现的次数删除条目 [英] Python Pandas: remove entries based on the number of occurrences

查看:394
本文介绍了Python Pandas:根据出现的次数删除条目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从数据帧中删除少于100次的条目. 数据帧data看起来像这样:

I'm trying to remove entries from a data frame which occur less than 100 times. The data frame data looks like this:

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

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

Now I count the number of tag occurrences like this:

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

但是后来我不知道如何删除那些计数低的条目...

But then I can't figure out how to remove those entries which have low count...

推荐答案

感谢@WesMcKinney显示了这种更直接的方法:

Thanks to @WesMcKinney for showing this much more direct way:

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

这篇关于Python Pandas:根据出现的次数删除条目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆