如何根据值计数过滤pandas DataFrame?

时间:2023-02-02 07:19:33

I'm working in Python with a pandas DataFrame of video games, each with a genre. I'm trying to remove any video game with a genre that appears less than some number of times in the DataFrame, but I have no clue how to go about this. I did find a * question that seems to be related, but I can't decipher the solution at all (possibly because I've never heard of R and my memory of functional programming is rusty at best).

我正在使用Python的大熊猫DataFrame开发视频游戏,每个都有一个类型。我试图删除任何在DataFrame中出现少于一些次数的类型的视频游戏,但我不知道如何解决这个问题。我确实找到了一个似乎相关的*问题,但我根本无法破译解决方案(可能是因为我从未听说过R,而且我对函数式编程的记忆充其量也是生锈的)。

Help?

1 个解决方案

#1


39  

Use groupby filter:

使用groupby过滤器:

In [11]: df = pd.DataFrame([[1, 2], [1, 4], [5, 6]], columns=['A', 'B'])

In [12]: df
Out[12]:
   A  B
0  1  2
1  1  4
2  5  6

In [13]: df.groupby("A").filter(lambda x: len(x) > 1)
Out[13]:
   A  B
0  1  2
1  1  4

I recommend reading the split-combine-section of the docs.

我建议阅读文档的split-combine-section。

#1


39  

Use groupby filter:

使用groupby过滤器:

In [11]: df = pd.DataFrame([[1, 2], [1, 4], [5, 6]], columns=['A', 'B'])

In [12]: df
Out[12]:
   A  B
0  1  2
1  1  4
2  5  6

In [13]: df.groupby("A").filter(lambda x: len(x) > 1)
Out[13]:
   A  B
0  1  2
1  1  4

I recommend reading the split-combine-section of the docs.

我建议阅读文档的split-combine-section。