Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Coordinates of item on NumPy array

Tags:

python

numpy

I have a NumPy array:

[[  0.   1.   2.   3.   4.]
 [  7.   8.   9.  10.   4.]
 [ 14.  15.  16.  17.   4.]
 [  1.  20.  21.  22.  23.]
 [ 27.  28.   1.  20.  29.]]

which I want to quickly find the coordinates of specific values and avoid Python loops on the array. For example the number 4 is on:

row 0 and col 4
row 1 and col 4
row 2 and col 4

and a search function should return a tuple:

((0,4),(1,4),(2,4))

Can this be done directly via NunmPy's functions?

like image 781
Ηλίας Avatar asked Mar 30 '11 14:03

Ηλίας


People also ask

How do you get the positions where elements of two arrays match NumPy?

import numpy as np A = np. array([[1, 1], [2, 2]]) B = np. array([[1, 1], [2, 2]]) print(A == B) In this resulting matrix, each element is a result of a comparison of two corresponding elements in the two arrays.

How do you find the most common element in a NumPy array in Python?

Steps to find the most frequency value in a NumPy array: Create a NumPy array. Apply bincount() method of NumPy to get the count of occurrences of each element in the array. The n, apply argmax() method to get the value having a maximum number of occurrences(frequency).

How do I find an element in an array Python?

Python has a method to search for an element in an array, known as index(). If you would run x. index('p') you would get zero as output (first index).


2 Answers

If a is your array, then you could use:

ii = np.nonzero(a == 4)

or

ii = np.where(a == 4)

If you really want a tuple, you can convert from the tuple of arrays to the tuple of tuples, but the return value from the numpy functions is convient for then doing other operations on your array.

Conversion to a tuple for the OP's specification:

tuple(zip(*ii))
like image 123
JoshAdel Avatar answered Oct 24 '22 18:10

JoshAdel


a = numpy.array([[  0.,  1.,  2.,  3.,  4.],
                 [  7.,  8.,  9., 10.,  4.],
                 [ 14., 15., 16., 17.,  4.],
                 [  1., 20., 21., 22., 23.],
                 [ 27., 28.,  1., 20., 29.]])
print numpy.argwhere(a == 4.)

prints

[[0 4]
 [1 4]
 [2 4]]

The usual caveats for floating point comparisons apply.

like image 37
Sven Marnach Avatar answered Oct 24 '22 19:10

Sven Marnach