I want to forward fill a pandas series conditionally based on the last valid index in the series. For example, say we have this series:
import pandas as pd
ser = pd.Series(['a', 'b', 'b', pd.NA, 'c', pd.NA, pd.NA, 'd', pd.NA])
ser
0 a
1 b
2 b
3 <NA>
4 c
5 <NA>
6 <NA>
7 d
8 <NA>
I would like to ffill() the series only if the last valid index was not 2. This is the desired result:
0 a
1 b
2 b
3 <NA>
4 c
5 c
6 c
7 d
8 d
I came up with this way which works, but does not seem like a great answer. Is there a more elegant way of doing this?
ffilled = ser.ffill()
shifted = ser.shift(1)
result = ffilled.loc[(~pd.isna(ser)) | (shifted != 'b')]
result
0 a
1 b
2 b
4 c # -> index 3 does not get forward filled
5 c
6 c
7 d
8 d
Concatenating this result back with the original would insert a NaN at index 3, so this works but making two intermediary versions of the series doesn't seem like a great solution.