There is an arr array with data (in fact, they are not important).

arr = np.array([[1,2,3],[4,5,6],[7,8,9]]) array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) 

It is necessary to obtain a list of coordinates of the center of each element of the array. It is assumed that the length of each cell is equal to 1. That is, you need to get the following:

 (0.5, 0.5) (0.5, 1.5) (0.5, 2.5) (1.5, 0.5) (1.5, 1.5) (1.5, 2.5) (2.5, 0.5) (2.5, 1.5) (2.5, 2.5) 

I do this:

 for row in range(arr.shape[0]): for col in range(arr.shape[1]): print (row + 0.5, col + 0.5) 

Actually a question. How to get rid of nested for each other? I feel - for sure there is some simple method from Numpy .

    2 answers 2

    Without for, you can do this:

     import numpy as np arr = np.arange(3 * 3).reshape(3, 3) grid = np.mgrid[:arr.shape[0], :arr.shape[1]] + 0.5 print(grid.reshape(2, -1).T) 

      If you need tuples coordinates, it’s better to use the @Avernial solution . If you need two separate arrays of coordinates X and Y , then you can use the function np.unravel_index () :

       In [291]: x, y = np.unravel_index(np.arange(arr.size), arr.shape) In [292]: x Out[292]: array([0, 0, 0, 1, 1, 1, 2, 2, 2], dtype=int64) In [293]: y Out[293]: array([0, 1, 2, 0, 1, 2, 0, 1, 2], dtype=int64) In [296]: x + 0.5 Out[296]: array([ 0.5, 0.5, 0.5, 1.5, 1.5, 1.5, 2.5, 2.5, 2.5]) In [297]: y + 0.5 Out[297]: array([ 0.5, 1.5, 2.5, 0.5, 1.5, 2.5, 0.5, 1.5, 2.5]) 

      You can also create an array of coordinates:

       In [305]: np.vstack(np.unravel_index(np.arange(arr.size), arr.shape)).T Out[305]: array([[0, 0], [0, 1], [0, 2], [1, 0], [1, 1], [1, 2], [2, 0], [2, 1], [2, 2]], dtype=int64) In [306]: np.vstack(np.unravel_index(np.arange(arr.size), arr.shape)).T + 0.5 Out[306]: array([[ 0.5, 0.5], [ 0.5, 1.5], [ 0.5, 2.5], [ 1.5, 0.5], [ 1.5, 1.5], [ 1.5, 2.5], [ 2.5, 0.5], [ 2.5, 1.5], [ 2.5, 2.5]])