Skip to content
Advertisement

Pandas dataframe getting specific row and columns

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?

Advertisement

Answer

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
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement