How to fill elements between intervals of a list

后端 未结 6 2337
无人及你
无人及你 2021-02-14 18:19

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

6条回答
  •  一整个雨季
    2021-02-14 18:39

    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]
    

提交回复
热议问题