python - 按出现次数分组

标签 python pandas dataframe counter pandas-groupby

您好,我想删除出现次数小于某个数字的条目的行,例如:

df = pd.DataFrame({'a': [1,2,3,2], 'b':[4,5,6,7], 'c':[0,1,3,2]})
df
   a  b  c
0  1  4  0
1  2  5  1
2  3  6  3
3  2  7  2

如果'a'列中的出现次数少于两次,我想删除所有行。
想要的输出:

   a  b  c
1  2  5  1
3  2  7  2

我所知道的: 我们可以通过 condition = df['a'].value_counts() < 2 找到出现的次数,它会给我这样的东西:

2    False
3    True
1    True
Name: a, dtype: int64

但我不知道应该如何从这里开始删除行。
提前致谢!

最佳答案

groupby + size

res = df[df.groupby('a')['b'].transform('size') >= 2]

transform方法将 df.groupby('a')['b'].size() 映射到与 df['a'] 对齐的 df .

value_counts + map

s = df['a'].value_counts()
res = df[df['a'].map(s) >= 2]

print(res)

   a  b  c
1  2  5  1
3  2  7  2

关于python - 按出现次数分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53471422/

相关文章:

python - Celery为每个任务实例安排了带有到期时间的任务?

python - 按条件过滤 pandas

python - 将多个测量值合并到 pandas 数据框中

dataframe - 如何过滤pyspark数据框中任何列为空的行

python - 使用 Python 对现有 SQL Server 数据库架构进行简单建模

python - 根据聚类按行划分seaborn矩阵

python - 从排列中清理元组列表

python - pandas 中的条件 cumsum

python - 将时间列添加到基于另一个 DataFrame 的 DataFrame

python - 使用 Scikit-learn (sklearn) 估算整个 DataFrame(所有列)而不迭代列