2

I am confused with the numpy.where and numpy.argwhere. For example,

 aa = (np.arange(10) + 5).reshape(2, -1)

If I run

 res = np.where(((aa == 7) | (aa == 8)))

Then

 >>> res
 (array([0, 0]), array([2, 3]))

If I run

 res2 = np.argwhere(((aa == 7) | (aa == 8)))

I get

 >>> res2
  array([[0, 2],
         [0, 3]])

Both numpy.where and numpy.argwhere give the coordinates of the nonzero elements in the boolean array. So if the inputs are boolean arrays, the two functions are basically doing the same thing. Is it correct?

1 Answer 1

3

If you look at the docs for np.where:

When only condition is provided, this function is a shorthand for np.asarray(condition).nonzero()

and nonzero returns a tuple of lists of indices for each dimension where the original array is non-zero (or false). np.argwhere on the other hand, returns a list of indices, that you can use to index into your original array. So in essence they are doing similar things, but to get the same output as np.argwhere from np.where you'd need to do:

np.vstack(np.where(((aa == 7) | (aa == 8)))).T

and the other way around:

a = np.argwhere(((aa == 7) | (aa == 8)))
tuple(a[:, i] for i in range(a.shape[1]))
Sign up to request clarification or add additional context in comments.

Comments

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.