Home > Back-end >  How to find the x, y coordinate (or index) of values in a 2D array
How to find the x, y coordinate (or index) of values in a 2D array

Time:11-08

I have a 2D array I created using this,

import numpy as np

arr = np.arange(4)
arr_2d = arr.reshape(2,2)   

The array looks like this

print(arr_2d)
[[0, 1],
 [2, 3]]

I am trying to get the location of each entry in arr_2d as an x, y coordinate, and eventually get an array that looks like this,

print(full_array)
[[0, 0, 0],
[1, 0, 1],
[2, 1, 0],
[3, 1, 1]]

Where the first column contains the values in arr_2d, the second column contains each value's x (or row) coordinate and the third column contains each value's y (or column) coordinate. I tried flattening arr_2d and enumerating to get the index of each entry, but I was unable to get it in this form. Any help will be much appreciated.

CodePudding user response:

Perhaps not the nicest way, but it works (assuming this is what you are after):

import numpy as np

arr = np.arange(4)
arr_2d = arr.reshape(2,2)  

arr_2d[1][0] = 5 # to illustrate a point

print(arr_2d)
dimensions = arr_2d.shape
for y in range(dimensions[0]):
    for x in range(dimensions[1]):
        print(arr_2d[x][y], " (x:", x, " y:", y, ")")

renders:

[[0 1]
 [5 3]]
0  (x: 0  y: 0 )
1  (x: 1  y: 0 )
5  (x: 0  y: 1 )
3  (x: 1  y: 1 )

which you can just put in another array

CodePudding user response:

You can use np.unravel_index():

x = arr_2d.flatten()
r = np.vstack((x,np.unravel_index(np.arange(arr_2d.size),arr_2d.shape))).T

# r = array([[0, 0, 0],
#           [1, 0, 1],
#           [2, 1, 0],
#           [3, 1, 1]], dtype=int64)

Both flatten() and np.unravel_index() use by default a row-major order, so we knows that the right order is preserved.

  • Related