I have a list like this:
list_1 = [np.NaN, np.NaN, 1, np.NaN, np.NaN, np.NaN, 0, np.NaN, 1, np.NaN, 0, 1, np.NaN, 0, np.NaN, 1, np.NaN]
So the
Pandas solution:
s = pd.Series(list_1)
s1 = s.eq(1)
s0 = s.eq(0)
m = (s1 | s0).where(s1.cumsum().ge(1),False).cumsum().mod(2).eq(1)
s.loc[m & s.isna()] = 1
print(s.tolist())
#[nan, nan, 1.0, 1.0, 1.0, 1.0, 0.0, nan, 1.0, 1.0, 0.0, 1.0, 1.0, 0.0, nan, 1.0, 1.0]
but if there is only 1
, 0
or NaN
you can do:
s = pd.Series(list_1)
s.fillna(s.ffill().where(lambda x: x.eq(1))).tolist()
output
[nan,
nan,
1.0,
1.0,
1.0,
1.0,
0.0,
nan,
1.0,
1.0,
0.0,
1.0,
1.0,
0.0,
nan,
1.0,
1.0]