python - 根据 pandas 中定义类别的列过滤掉观察数量不足的 DataFrame 行

标签 python pandas dataframe filtering counter

我有一个 DataFrame,其中有一列将数据集划分为一组类别。我想删除那些观察次数较少的类别。

示例

df = pd.DataFrame({'c': ['c1', 'c2', 'c1', 'c3', 'c4', 'c5', 'c2'], 'v': [5, 2, 7, 1, 2, 8, 3]})

    c  v
0  c1  5
1  c2  2
2  c1  7
3  c3  1
4  c4  2
5  c5  8
6  c2  3

对于列 cn = 2,删除列 c< 中具有小于 n 相同值的所有行,结果是:

    c  v
0  c1  5
1  c2  2
2  c1  7
3  c2  3

最佳答案

使用pd.Series.value_counts随后通过 pd.Series.isin 进行 bool 索引:

counts = df['c'].value_counts()  # create series of counts
idx = counts[counts < 2].index   # filter for indices with < 2 counts

res = df[~df['c'].isin(idx)]     # filter dataframe

print(res)

    c  v
0  c1  5
1  c2  2
2  c1  7
6  c2  3

关于python - 根据 pandas 中定义类别的列过滤掉观察数量不足的 DataFrame 行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52273000/

相关文章:

python - 在截取屏幕截图的脚本中出现错误, undefined variable

Python/Pandas - 删除以字符串开头的列

验证后枚举值为 'Not a valid choice' 的 Python Flask WTForm SelectField

Python - 时间序列对齐和 "to date"函数

python - xlsxwriter 中条件匹配时添加列

python - 如何计算python中每行具有值的列数?

python - append 到 pandas 数据框中的列表

r - 使用 dplyr 包 R 改变 data.frame 或 tibble 中的选定列

python - 要插入数据框-pandas 中的选定行

python - 如何在 Python 中调用默认的字符串相等函数?