How to fill elements between intervals of a list

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

    You can retrieve indices one ones and zeros using np.argwhere and then fill the values among each slice:

    import numpy as np
    
    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])
    
    ones = np.squeeze(np.argwhere(a==1))
    zeros = np.squeeze(np.argwhere(a==0))
    
    if ones[0]>zeros[0]:
        zeros = zeros[1:]
    
    value = -999
    for i,j in zip(ones,zeros):
        a[i+1:j] = value
    
    a
    array([  nan,   nan,    1., -999., -999., -999.,    0.,   nan,    1.,
           -999.,    0.,    1., -999.,    0.,   nan,    1.,   nan])
    

提交回复
热议问题