-2

Pandas dataframe has

 FRUIT      DATE  PRICE
 Apple 11/5/2021     10
 Apple 12/5/2021     11
 Apple 13/5/2021     15
Orange 11/5/2021     20
Orange 12/5/2021     29
Orange 13/5/2021     15
Banana 11/5/2021      5
Banana 12/5/2021      7
Banana 13/5/2021      6

Data in pandas dataframe I need data of first two dates of every fruit name like

 FRUIT      DATE  PRICE
 Apple 11/5/2021     10
 Apple 12/5/2021     11
Banana 11/5/2021      5
Banana 12/5/2021      7
Orange 11/5/2021     20
Orange 12/5/2021     29

I have more than 100 fruit names

How to write condition for filtering the data?

1
  • When asking a question you should include an example of what you have tried so far, if you have not tried anything yet you might need to do some research before asking a question. Commented Aug 13, 2021 at 22:49

1 Answer 1

1

Sort by DATE then groupby FRUIT and keep 2 first rows of each group:

>>> df.sort_values('DATE').groupby('FRUIT').head(2).sort_values('FRUIT')

    FRUIT       DATE  PRICE
0   Apple  11/5/2021     10
1   Apple  12/5/2021     11
6  Banana  11/5/2021      5
7  Banana  12/5/2021      7
3  Orange  11/5/2021     20
4  Orange  12/5/2021     29
Sign up to request clarification or add additional context in comments.

4 Comments

Edited my question, pls go through it
@hariprasad. I updated my answer.

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.