首页 > 解决方案 > Filtering dataframe rows based on count

问题描述

I have a table like

Fruit   Month
----------------
A   Jan
A   Feb
A   Mar 
B   Sep

I want to filter the table in such a way that I get only top n rows say two for each fruit Example

Fruit   Month
----------------
A   Jan
A   Feb 
B   Sep

标签: pythonpandasdataframe

解决方案


You can just use groupby() and head():

df.groupby('Fruit').head(2)

Outputs:

  Fruit Month
0     A   Jan
1     A   Feb
3     B   Sep

推荐阅读