Create an array where each element stores its indices

后端 未结 4 906
粉色の甜心
粉色の甜心 2020-12-19 11:56

I want to create a 2d numpy array where every element is a tuple of its indices.

Example (4x5):

array([[[0, 0],
        [0, 1],
        [0, 2],
              


        
4条回答
  •  [愿得一人]
    2020-12-19 12:18

    You can abuse numpy.mgrid or meshgrid for this purpose:

    >>> import numpy as np
    >>> np.mgrid[:4,:5].transpose(1,2,0)
    array([[[0, 0],
            [0, 1],
            [0, 2],
            [0, 3],
            [0, 4]],
    
           [[1, 0],
            [1, 1],
            [1, 2],
            [1, 3],
            [1, 4]],
    
           [[2, 0],
            [2, 1],
            [2, 2],
            [2, 3],
            [2, 4]],
    
           [[3, 0],
            [3, 1],
            [3, 2],
            [3, 3],
            [3, 4]]])
    

提交回复
热议问题