Home > Mobile >  Get coordinates with np.where() in Python
Get coordinates with np.where() in Python

Time:10-14

I am trying whole day to figure out how to solve this problem, but without success. First the code:

a = np.arange(15).reshape(5, 3)
b = np.arange(15).reshape(5, 3)
c = np.arange(10, 25).reshape(5, 3)
c[4, 0] = 1
c[4, 1] = 1

print(a)
print(b)
print(c)

y, x = np.where(a > 10)
coord = list(zip(y, x))
print(coord)

y, x = np.where(b[y, x] > c[y, x]) # this line produces error and know why

So I want to get coordinates of elements that are > 10 in 2d array a. Then I want to use these coordinates to compare element-wise values on these positions in 2d arrays b and c. And if element from b is greater then element from c on position, I want coordinates of that position.

So for above code np.where(a > 10) gives me coordinates: [(3, 2), (4, 0), (4, 1), (4, 2)]

And then I'm comparing on these coordinates elements from b and c. I would have at the end coordinates (4,0) and (4,1) because only on these positions element from b is greater than element from c.

Thank you!

CodePudding user response:

The error happens because the expression:

b[y, x] > c[y, x] # the output is [False  True  True False]

returns a 1-dimensional array. And therefore np.where returns a tuple of size 1 (corresponding to the dimension the input).

np.where(b[y, x] > c[y, x]) # the output is (array([1, 2]),)

One possible solution is to do:

y, x = np.where(a > 10)
coord = np.array(list(zip(y, x)))

y = np.where(b[y, x] > c[y, x])
result = coord[y]
print(result)

Output

[[4 0]
 [4 1]]

As an alternative, if you want to keep the list of tuples output, do:

y, x = np.where(a > 10)
coord = list(zip(y, x))

y = np.where(b[y, x] > c[y, x])
result = [tt for i, tt in enumerate(coord) if i in y[0]]
print(result)

Output

[(4, 0), (4, 1)]
  • Related