Fill in values between given indices of 2d numpy array

后端 未结 1 747
礼貌的吻别
礼貌的吻别 2021-01-03 12:02

Given a numpy array,

a = np.zeros((10,10))

[[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0,          


        
相关标签:
1条回答
  • 2021-01-03 12:22

    You can use broadcasting -

    r = np.arange(10)[:,None]
    out = ((start  <= r) & (r <= end)).astype(int)
    

    This would create an array of shape (10,len(start). Thus, if you need to actually fill some already initialized array filled_arr, do -

    m,n = out.shape
    filled_arr[:m,:n] = out
    

    Sample run -

    In [325]: start = [0,1,2,3,4,4,3,2,1,0]
         ...: end   = [9,8,7,6,5,5,6,7,8,9]
         ...: 
    
    In [326]: r = np.arange(10)[:,None]
    
    In [327]: ((start  <= r) & (r <= end)).astype(int)
    Out[327]: 
    array([[1, 0, 0, 0, 0, 0, 0, 0, 0, 1],
           [1, 1, 0, 0, 0, 0, 0, 0, 1, 1],
           [1, 1, 1, 0, 0, 0, 0, 1, 1, 1],
           [1, 1, 1, 1, 0, 0, 1, 1, 1, 1],
           [1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
           [1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
           [1, 1, 1, 1, 0, 0, 1, 1, 1, 1],
           [1, 1, 1, 0, 0, 0, 0, 1, 1, 1],
           [1, 1, 0, 0, 0, 0, 0, 0, 1, 1],
           [1, 0, 0, 0, 0, 0, 0, 0, 0, 1]])
    

    If you meant to use this as a mask with 1s as the True ones, skip the conversion to int. Thus, (start <= r) & (r <= end) would be the mask.

    0 讨论(0)
提交回复
热议问题