Create an array where each element stores its indices

后端 未结 4 913
粉色の甜心
粉色の甜心 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条回答
  •  旧时难觅i
    2020-12-19 12:20

    Do you do this because you need it or just for sport? In the former case:

    np.moveaxis(np.indices((4,5)), 0, -1)
    

    np.indices does precisely what its name suggests. Only it arranges axes differently to you. So we move them with moveaxis

    As @Eric points out one attractive feature of this method is that it works unmodified at arbitrary number of dimensions:

    dims = tuple(np.multiply.reduceat(np.zeros(16,int)+2, np.r_[0, np.sort(np.random.choice(16, np.random.randint(10)))]))
    # len(dims) == ?
    np.moveaxis(np.indices(dims), 0, -1) # works
    

提交回复
热议问题