I have a dataframe like this one:
a1 l1
0 a NaN
1 a kl
2 a NaN
3 a NaN
4 a er
5 b ye
6 b NaN
7 b fk
8 b NaN
What I want is, the last previous non-null value of l1 for each group of a1 values. So the expected output is:
a1 l1 ex
0 a NaN NaN
1 a kl NaN
2 a NaN kl
3 a NaN kl
4 a er kl
5 b ye NaN
6 b NaN ye
7 b fk ye
8 b NaN fk
I have tried to use shift but I don´t know how to skip missing values.
You'll need groupby
and apply
here:
df['ex'] = df.groupby('a1').l1.apply(lambda x: x.ffill().shift())
df
a1 l1 ex
0 a NaN NaN
1 a kl NaN
2 a NaN kl
3 a NaN kl
4 a er kl
5 b ye NaN
6 b NaN ye
7 b fk ye
8 b NaN fk
Alternatively, chain two groupby
calls in succession:
df['ex'] = df.groupby('a1').ffill().groupby('a1').shift()
df
a1 l1 ex
0 a NaN NaN
1 a kl NaN
2 a NaN kl
3 a NaN kl
4 a er kl
5 b ye NaN
6 b NaN ye
7 b fk ye
8 b NaN fk
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.