You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Pandas过滤groupby+value_counts中频率小于2的统计结果

解决Pandas中过滤groupby后value_counts低频条目的问题

没问题,这就帮你搞定这个需求!先对照你的示例数据和当前结果,我们可以用两种简单的方式实现过滤频次小于2的条目:

方法一:直接对value_counts结果过滤

value_counts()返回的Series本身就包含频次值,我们可以直接用布尔索引筛选出频次≥2的条目,再重置索引得到目标格式:

import pandas as pd

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']})

# 计算分组后的频次
grouped_counts = df.groupby('A')['B'].value_counts()

# 过滤频次≥2的行,重置索引并命名频次列
filtered_result = grouped_counts[grouped_counts >= 2].reset_index(name='freq')

print(filtered_result)

执行后输出就是你想要的结果:

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

方法二:先分组计算大小再过滤

如果你更习惯先得到带列的DataFrame再操作,可以先按A和B双重分组计算大小,再进行过滤:

# 先得到包含所有频次的DataFrame
full_counts = df.groupby(['A', 'B']).size().reset_index(name='freq')

# 过滤出频次≥2的条目
filtered_result = full_counts[full_counts['freq'] >= 2]

这个方法的输出和上面完全一致,两种方式都能满足你的需求,选你觉得顺手的就行~

内容的提问来源于stack exchange,提问作者Guillaume Lombard

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 10:02:54