Pandas groupby value_count 按频率过滤 [英] Pandas groupby value_count filter by frequency

查看:155
本文介绍了Pandas groupby value_count 按频率过滤的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想过滤掉小于 n 的频率,在我的例子中 n 是 2

df = pd.DataFrame({'A' : ['foo', 'bar', 'foo', 'bar', 'foo', 'bar','foo', 'bar','foo', 'bar',],'B' : ['yes', 'no', 'yes', 'no', 'no', 'yes','yes', 'no', 'no', '不']})df.groupby('A')['B'].value_counts()甲乙酒吧没有 4是 1foo 是 3没有 2名称:B,数据类型:int64

理想情况下,我希望数据框中的结果显示如下(不排除 1 的频率)

A B 频率酒吧没有 4foo 是 3没有 2

我试过了

df.groupby('A')['B'].filter(lambda x: len(x) > 1)

但这失败了,因为显然 groupby 返回了一个系列

解决方案

这可以用一行 .loc

<预><代码>>>>df.groupby('A')['B'].value_counts().loc[lambda x: x >1].reset_index(name='count')A B 计数0 酒吧没有 41 foo 是 32 foo 没有 2

I would like to filter out the frequencies that are less than n, in my case n is 2

df = pd.DataFrame({'A' : ['foo', 'bar', 'foo', 'bar', 'foo', 'bar','foo', 'bar', 'foo', 'bar',],'B' : ['yes', 'no', 'yes', 'no', 'no', 'yes','yes', 'no', 'no', 'no']})
df.groupby('A')['B'].value_counts()

A    B  
bar  no     4
     yes    1
foo  yes    3
     no     2
Name: B, dtype: int64

Ideally I would like the results in a dataframe showing the below(frequency of 1 is not excluded)

A    B      freq
bar  no     4
foo  yes    3
foo  no     2

I have tried

df.groupby('A')['B'].filter(lambda x: len(x) > 1)

but this fails as apparently groupby returns a serie

解决方案

This can be down with one line with .loc

>>> df.groupby('A')['B'].value_counts().loc[lambda x: x > 1].reset_index(name='count')
     A    B  count
0  bar   no      4
1  foo  yes      3
2  foo   no      2

这篇关于Pandas groupby value_count 按频率过滤的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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