0

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

1 Answer 1

2

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

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

Outputs:

  Fruit Month
0     A   Jan
1     A   Feb
3     B   Sep
Sign up to request clarification or add additional context in comments.

4 Comments

ahh i think i got this question wrong. Guessed its based on months
Yeah, I wasn't entirely sure what the OP was aiming for, but this seems to be the most simplistic way to achieve their desired output.
This works like a charm but the issue I have is it does not maintain the initial order of top two but selects random two. Is there a way to solve that?
It will not select a random two, can you please include a revised example in your original post with what you are observing?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.