Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to find max value with shift and condition?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading