rrlamichhane
rrlamichhane

Reputation: 1685

How can I find a minimum or maximum of a column for 'n' number of rows of data in Pandas Dataframe?

I couldn't find an answer to this anywhere. I need to find minimum value for a column, let's say A, for last n number of rows.

I saw solutions where I can find the minimum of the whole column, or different columns, but couldn't find a way to calculate minimum (or maximum) for a column for a window of only certain rows.

e.g.

     A   B   C   D   Amin10   Bmax5
0   13  13  10   4
1    8   0  15  14
2   12   7   7   9
3   22  11  22   2
4    2   2  12   3
5   18  24  20  14
6    6  18  20  22
7    3   8   2  13
8   21   9  11   4
9    2   2  14  21
10  15   0   9  17
11  11  19  22   2
12  18   2  10  13
13  14  20  20  10
14   8   8  22  16

Let's say I want a column 'Amin10' that has minimum values from column A in the last 10 rows, and 'Bmax5' that has maximum values from column B in the last 5 rows.

How can I achieve this?

Thanks.

Upvotes: 1

Views: 135

Answers (1)

piRSquared
piRSquared

Reputation: 294536

use rolling

df['Amin10'] = df.A.rolling(10).min()
df['Bmax5'] = df.B.rolling(5).max()
print(df)

     A   B   C   D  Amin10  Bmax5
0   13  13  10   4     NaN    NaN
1    8   0  15  14     NaN    NaN
2   12   7   7   9     NaN    NaN
3   22  11  22   2     NaN    NaN
4    2   2  12   3     NaN   13.0
5   18  24  20  14     NaN   24.0
6    6  18  20  22     NaN   24.0
7    3   8   2  13     NaN   24.0
8   21   9  11   4     NaN   24.0
9    2   2  14  21     2.0   24.0
10  15   0   9  17     2.0   18.0
11  11  19  22   2     2.0   19.0
12  18   2  10  13     2.0   19.0
13  14  20  20  10     2.0   20.0
14   8   8  22  16     2.0   20.0

Upvotes: 3

Related Questions