3

I have seen the post Difference between nonzero(a), where(a) and argwhere(a). When to use which? and I don't really understand the use of the where function from numpy module.

For example I have this code

import numpy as np

Z =np.array( 
    [[1,0,1,1,0,0],
     [0,0,0,1,0,0],
     [0,1,0,1,0,0],
     [0,0,1,1,0,0],
     [0,1,0,0,0,0],
     [0,0,0,0,0,0]])
print Z
print np.where(Z)

Which gives:

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

The definition of where function is: Return elements, either from x or y, depending on condition. But it doesn't also makes sense to me

So what does the output exactly mean?

1
  • 1
    When you call it as np.where(condition, x, y) it does what you have quoted. If you omit the x and y arguments is is equivalent to np.nonzero. Commented Jan 22, 2014 at 16:41

1 Answer 1

3

np.where returns indices where a given condition is met. In your case, you're asking for the indices where the value in Z is not 0 (e.g. Python considers any non-0 value as True). Which for Z results in:

(0, 0) # top left
(0, 2) # third element in the first row
(0, 3) # fourth element in the first row
(1, 3) # fourth element in the second row
...    # and so on

np.where starts to make sense in the following scenarios:

a = np.arange(10)
np.where(a > 5) # give me all indices where the value of a is bigger than 5
# a > 5 is a boolean mask like [False, False, ..., True, True, True]
# (array([6, 7, 8, 9], dtype=int64),)

Hope that helps.

Sign up to request clarification or add additional context in comments.

1 Comment

does numpy.where loops the entire array?

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.