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:
CodePudding user response:
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
CodePudding user response:
You can use two masks for finding vals
and idxs
and set values to index for result
column.
mask1 = df['BrkPressState'] != df['BrkPressState'].shift()
vals = df.loc[mask1, 'VehSpdGS'][1:].values
mask2 = df['BrkPressState'] != df['BrkPressState'].shift(-1)
idxs = df.loc[mask2, 'VehSpdGS'][:-1].index
df.loc[idxs, 'result'] = vals
print(df)
BrkPressState VehSpdGS result
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
CodePudding user response:
You can also do shift(-1)
on VehSpdGS
and then replace values with NaN
if df['BrkPressState'] != df['BrkPressState'].shift(-1)
Code:
df["result"]=df["VehSpdGS"].shift(-1).where(df['BrkPressState'] != df['BrkPressState'].shift(-1),pd.NA)
df
output:
BrkPressState | VehSpdGS | result | |
---|---|---|---|
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 |