How to fill elements between intervals of a list

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

    Assuming each 1 is followed by 0 (minus last 1):

    list_1 = 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])
    zeros_ind = np.where(list_1 == 0)[0]
    ones_ind = np.where(list_1 == 1)[0]
    ones_ind = ones_ind[:zeros_ind.size]
    
    #create a concatenated list of ranges of indices you desire to slice
    indexer = np.r_[tuple([np.s_[i:j] for (i,j) in zip(ones_ind,zeros_ind)])]
    #slice using numpy indexing
    list_1[indexer] = 1
    

    Output:

    [nan nan  1.  1.  1.  1.  0. nan  1.  1.  0.  1.  1.  0. nan  1. nan]
    

提交回复
热议问题