How to fill elements between intervals of a list

后端 未结 6 2317
无人及你
无人及你 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:28

    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])
    

提交回复
热议问题