gpt4 book ai didi

Python Pandas : exclude rows below a certain frequency count

转载 作者:太空宇宙 更新时间:2023-11-03 20:55:57 24 4
gpt4 key购买 nike

所以我有一个如下所示的 pandas DataFrame:

r vals    positions
1.2 1
1.8 2
2.3 1
1.8 1
2.1 3
2.0 3
1.9 1
... ...

我希望按位置过滤掉未出现至少 20 次的所有行。我见过这样的事情

g=df.groupby('positions')
g.filter(lambda x: len(x) > 20)

但这似乎不起作用,我不明白如何从中获取原始数据帧。预先感谢您的帮助。

最佳答案

在有限的数据集上,以下工作有效:

In [125]:
df.groupby('positions')['r vals'].filter(lambda x: len(x) >= 3)

Out[125]:
0 1.2
2 2.3
3 1.8
6 1.9
Name: r vals, dtype: float64

您可以分配此过滤器的结果并将其与isin一起使用过滤您的原始 df:

In [129]:
filtered = df.groupby('positions')['r vals'].filter(lambda x: len(x) >= 3)
df[df['r vals'].isin(filtered)]

Out[129]:
r vals positions
0 1.2 1
1 1.8 2
2 2.3 1
3 1.8 1
6 1.9 1

您只需根据您的情况将 3 更改为 20

另一种方法是使用 value_counts要创建聚合系列,我们可以使用它来过滤您的 df:

In [136]:
counts = df['positions'].value_counts()
counts

Out[136]:
1 4
3 2
2 1
dtype: int64

In [137]:
counts[counts > 3]

Out[137]:
1 4
dtype: int64

In [135]:
df[df['positions'].isin(counts[counts > 3].index)]

Out[135]:
r vals positions
0 1.2 1
2 2.3 1
3 1.8 1
6 1.9 1

编辑

如果您想过滤数据帧上的 groupby 对象而不是 Series,那么您可以调用 filter直接在 groupby 对象上:

In [139]:
filtered = df.groupby('positions').filter(lambda x: len(x) >= 3)
filtered

Out[139]:
r vals positions
0 1.2 1
2 2.3 1
3 1.8 1
6 1.9 1

关于Python Pandas : exclude rows below a certain frequency count,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56029205/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com