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

Populate next row event in current row based on the event in Pandas dataframe

BrkPressState VehSpdGS
1 2
1 3
1 2
1 4
0 12
0 13
0 11
1 3
0 15
0 14
0 15
1 12
1 13
0 14

For the above table i am trying to populate the next row value in previous last event, Like the below table

I tried with Shift – 1 but its populating only for the current row , Sample code which i tried.

d['result']=d.loc[d['BrkPressState'] != d['BrkPressState'].shift(-1), 'VehSpdGS'] 

Expected output:

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

enter image description here

>Solution :

Let us do diff to compare the previous and current row in BrkPressState column in order to identify boundaries, then mask and shift the values in VehSpdGS column

m = df['BrkPressState'].diff().ne(0)
df['Results'] = df['VehSpdGS'].mask(~m).shift(-1)

    BrkPressState  VehSpdGS  Results
0               1         2      NaN
1               1         3      NaN
2               1         2      NaN
3               1         4     12.0
4               0        12      NaN
5               0        13      NaN
6               0        11      3.0
7               1         3     15.0
8               0        15      NaN
9               0        14      NaN
10              0        15     12.0
11              1        12      NaN
12              1        13     14.0
13              0        14      NaN
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