Skip to content
Advertisement

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:

enter image description here

Advertisement

Answer

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
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement