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

Check if Value Greater than Previous Row by Group

With the dataframe below I want to compare the values in Val1 with the value in the preceding row by group. I then want to create a new column containing the word "Abv" if the value is greater than the preceding row and "Blw" if the value is lower than the predecing row. If the values are equal the new column should be blank.

Here’s an extract:

Ref1 Val1
A 1
A 2
A 3
A 4
B 1
B 1
B 2
B 0

Desired 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

Ref1 Val1 AbvBlw
A 1
A 2 Abv
A 3 Abv
A 4 Abv
B 1
B 1
B 2 Abv
B 0 Blw

>Solution :

Code

get groupby diff & chk condition

boolean masking with np.select

import numpy as np
s = df.groupby(['Ref1'])['Val1'].diff()
df['AbwBlw'] = np.select([s > 0, s == 0, s < 0], ['Abw', None, 'Blw'], None)

df

     Ref1  Val1 AbwBlw
0    A     1    None
1    A     2    Abw
2    A     3    Abw
3    A     4    Abw
4    B     1    None
5    B     1    None
6    B     2    Abw
7    B     0    Blw
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