24

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?

2 Answers 2

31

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))
Sign up to request clarification or add additional context in comments.

Comments

25
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.

6 Comments

Just as a note from the documentation "The output of np.argwhere is not suitable for indexing arrays. For this purpose use np.where(a) instead."
@JoshAdel: Why do you think the OP wants to use this for indexing? I chose the function that produces output that is closest to the OP's desired output.
@SvenMarnach: Could have gone with both, he just mentioned first the .where
@SvenMarnach: Don't be sad, you still have 17k rep points on me :-) But seriously, I also provided a means for getting the OP's desired output, but I also wanted to point out something about how numpy works that might be useful for others. It wasn't meant to be a knock on your solution, but some additional (and what I thought was useful) info.
@SvenMarnach, @JoshAdel It was also part concurrency issue, I think SO would have benefited if Google Wave was successful!
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.