python出现次数删除行_Python Pandas:根据出现的次数删除条目

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...

解决方案

Edit: 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)])

yields

pid tag

1 1 45

2 1 62

4 2 45

7 3 62

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值