Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

select top 2 rows every 5 rows in pandas

Tags:

python

pandas

I want to select top two rows every 5 rows in pandas dataframe. How could I do this?

Consider the following dataframe:

col1  | col2 | col3 
1     | 1    | 1
2.    | 2.   | 2
3.    | 3.   | 3 
4     | 4    | 4 
5.    | 5.   | 5 
6.    | 6.   | 6
7.    | 7.   | 7

I would like to get the following values

    col1  | col2 | col3 
    1     | 1    | 1
    2.    | 2.   | 2

and

    col1  | col2 | col3
    6.    | 6.   | 6
    7.    | 7.   | 7

I will really appreciate the help!!!

like image 324
sanster9292 Avatar asked Dec 30 '25 12:12

sanster9292


1 Answers

Use floor division on the index and groupby on it with head:

df.groupby(df.index//5).head(2)
like image 122
Henry Yik Avatar answered Jan 01 '26 02:01

Henry Yik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!