Home > Enterprise >  Pandas ffill for certain values in a column
Pandas ffill for certain values in a column

Time:10-12

I have a df like this:

time     data
0         1
1         1
2         nan
3         nan
4         6
5         nan
6         nan
7         nan
8         5
9         4
10        nan

Is there a way to use pd.Series.ffill() to ffill on for certain occurences of values? Specifically, I want to forward fill only if values in df.data are == 1 or 4. Should look like this:

time     data
0         1
1         1
2         1
3         1
4         6
5         nan
6         nan
7         nan
8         5
9         4
10        4

CodePudding user response:

One option would be to forward fill (ffill) the column, then only populate where the values are 1 or 4 using (isin) and (mask):

s = df['data'].ffill()
df['data'] = df['data'].mask(s.isin([1, 4]), s)

df:

    time  data
0      0   1.0
1      1   1.0
2      2   1.0
3      3   1.0
4      4   6.0
5      5   NaN
6      6   NaN
7      7   NaN
8      8   5.0
9      9   4.0
10    10   4.0
  • Related