How to select elements in numpy array with given starting point indices

前端 未结 2 730
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-28 05:45

For example, I have a matrix like this:

In [2]: a = np.arange(12).reshape(3, 4)

In [3]: a
Out[3]: 
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,         


        
2条回答
  •  旧巷少年郎
    2021-01-28 06:12

    This aproach works for rectangular matrices too. Create a boolean mask trough broadcasting:

    a = np.arange(12).reshape(3, 4)
    idx = np.array([1, 2, 0])
    mask=np.arange(a.shape[1]) >= idx[:,None]
    mask
    #array([[False,  True,  True,  True],
    #       [False, False,  True,  True],
    #       [ True,  True,  True,  True]], dtype=bool)
    

    Make your placeholder -1, for example, and set the values of a where mask is true equal to that placeholder:

    x = -1
    a[mask] = x
    a
    #array([[ 0, -1, -1, -1],
    #       [ 4,  5, -1, -1],
    #      [-1, -1, -1, -1]])
    

提交回复
热议问题