I have Dataframe like this:
Index A
0 3
1 2
2 5
3 4
4 1
5 2
6 7
7 3
8 1
And i need to go with the shift, taking 5 pieces and so that the maximum is in the center of them.
Result:
Index A Res
0 3 0
1 2 0
2 5 5
3 4 0
4 1 0
5 2 0
6 7 7
7 3 0
8 1 0
How can i implement this using pandas methods?
>Solution :
You can use rolling with the center=True and step=5 parameters:
N = 5
df.loc[N//2::N, 'Res'] = (df['A'].rolling(N, center=True, min_periods=1, step=N)
.max().values
)
Output:
Index A Res
0 0 3 NaN
1 1 2 NaN
2 2 5 5.0
3 3 4 NaN
4 4 1 NaN
5 5 2 NaN
6 6 7 NaN
7 7 3 7.0
8 8 1 NaN
If you want the 0s either pre-fill the columns with them (df['Res'] = 0) or use @Corralien’s approach from comments with a mask:
df['Res'] = (df.rolling(5, center=True, min_periods=1)['A'].max()
.where(lambda x: x == df['A'], 0).convert_dtypes()
)
Output:
Index A Res
0 0 3 0
1 1 2 0
2 2 5 5
3 3 4 0
4 4 1 0
5 5 2 0
6 6 7 7
7 7 3 0
8 8 1 0