Quim Quadrada
Quim Quadrada

Reputation: 45

Find maximum and minimum value of five consecutive rows by column

I want to get the maximum and minimum value of some columns grouped by 5 consecutive values. Example, I want to have maximum by a and minimum by b, of 5 consecutive rows

   a  b
0  1  2
1  2  3
2  3  4
3  2  5
4  1  1
5  3  6
6  2  8
7  5  2
8  4  6
9  2  7

I want to have

   a  b
0  3  1
1  5  2

(Where 3 is the maximum of 1,2,3,2,1 and 1 is the minumum of 2,3,4,5,1, and so on)

Upvotes: 0

Views: 153

Answers (1)

user17242583
user17242583

Reputation:

Use integer division (//) to form the index for grouping by every 5 items, and then use groupby and agg:

out = df.groupby(df.index // 5).agg({'a':'max', 'b':'min'})

Output:

>>> out
   a  b
0  3  1
1  5  2

Upvotes: 1

Related Questions