Generate NumPy array containing the indices of another NumPy array

前端 未结 1 1942
名媛妹妹
名媛妹妹 2021-01-24 19:08

I\'d like to generate a np.ndarray NumPy array for a given shape of another NumPy array. The former array should contain the corresponding indices for each cell of

相关标签:
1条回答
  • 2021-01-24 19:36

    One way to do it with np.indices and np.stack:

    np.stack(np.indices((3,)), -1)
    
    #array([[0],
    #       [1],
    #       [2]])
    
    np.stack(np.indices((3,2)), -1)
    
    #array([[[0, 0],
    #        [0, 1]],
    #       [[1, 0],
    #        [1, 1]],
    #       [[2, 0],
    #        [2, 1]]])
    

    np.indices returns an array of index grid where each subarray represents an axis:

    np.indices((3, 2))
    
    #array([[[0, 0],
    #        [1, 1],
    #        [2, 2]],        
    #       [[0, 1],
    #        [0, 1],
    #        [0, 1]]])
    

    Then transpose the array with np.stack, stacking index for each element from different axis:

    np.stack(np.indices((3,2)), -1)
    
    #array([[[0, 0],
    #        [0, 1]],
    #       [[1, 0],
    #        [1, 1]],
    #       [[2, 0],
    #        [2, 1]]])
    
    0 讨论(0)
提交回复
热议问题