[英]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.我尝试使用 Shift - 1 但它仅填充当前行,我尝试过的示例代码。
d['result']=d.loc[d['BrkPressState'] != d['BrkPressState'].shift(-1), 'VehSpdGS']
Expected output:预期输出:
You can use two masks for finding vals
and idxs
and set values to index for result
column.您可以使用两个掩码来查找
vals
和idxs
,并将值设置为result
列的索引。
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
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让我们做
diff
来比较BrkPressState
列中的前一行和当前行以识别边界,然后mask
和shift
VehSpdGS
列中的值
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
You can also do shift(-1)
on VehSpdGS
and then replace values with NaN
if df['BrkPressState'] != df['BrkPressState'].shift(-1)
如果
df['BrkPressState'] != df['BrkPressState'].shift(-1)
你也可以在VehSpdGS
上做shift(-1)
然后用NaN
替换值
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![]() |
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.