pandas ffill/bfill for specific amount of observation

Viewed 5651

I have the following dataframe:

 id     indicator 
 1          NaN
 1          NaN
 1          1
 1          NaN
 1          NaN
 1          NaN

In reality, I have several more ids. My question now is, how do I do a forward or backward fill for a specific range, e.g. for only the next/last 2 observations. My dataframe should look like this:

 id     indicator 
 1          NaN
 1          NaN 
 1          1
 1          1
 1          1
 1          NaN

I know the command

df.groupby("id")["indicator"].fillna(value=None, method="ffill")         

However, this fills all the missing values instead of just the next two observations. Anyone knows a solution?

2 Answers
Related