How to fill elements between intervals of a list
Here's a numpy based approach using np.cumsum
:
a = np.array([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])
ix0 = (a == 0).cumsum()
ix1 = (a == 1).cumsum()
dec = (ix1 - ix0).astype(float)
# Only necessary if the seq can end with an unclosed interval
ix = len(a)-(a[::-1]==1).argmax()
last = ix1[-1]-ix0[-1]
if last > 0:
dec[ix:] = a[ix:]
# -----
out = np.where(dec==1, dec, a)
print(out)
array([nan, nan, 1., 1., 1., 1., 0., nan, 1., 1., 0., 1., 1.,
0., nan, 1., nan])
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]