Advertisements

I am trying to do the following:

Supposing I have the following column on pandas, where there will be always two values that are equal in sequence.

```
l = [np.nan, np.nan, 10, np.nan, np.nan, np.nan, 10, np.nan, 4, np.nan, 4, 5, np.nan, 5, np.nan, 2, np.nan, 2, 1, 1]
```

How can I fill NaN values only in between the interval of similar values ?

expected output:

```
[np.nan, np.nan, 10, 10, 10, 10, 10, np.nan, 4, 4, 4, 5, 5, 5, np.nan, 2, 2, 2, 1, 1]
```

I could only find this answer, which is not the same problem:

### >Solution :

### Solution with `ffill`

and `bfill`

```
f = df['col'].ffill()
b = df['col'].bfill()
df['col'].mask(f == b, f)
```

```
0 NaN
1 NaN
2 10.0
3 10.0
4 10.0
5 10.0
6 10.0
7 NaN
8 4.0
9 4.0
10 4.0
11 5.0
12 5.0
13 5.0
14 NaN
15 2.0
16 2.0
17 2.0
18 1.0
19 1.0
Name: col, dtype: float64
```