6

I am trying to use numpy_where to find the index of a particular value. Though I have searched quite a bit on the web including stackoverflow I did not find a simple 1D example.

ar=[3,1,4,8,2,1,0]
>>> np.where(ar==8)
(array([], dtype=int64),)

I expected np.where(ar==8) to return me the index/location of 8 in the the array. What am I doing wrong? Is it something in my array? Thanks

0

1 Answer 1

7

This is a really good example of how the range of variable types in Python and numpy can be confusing for a beginner. What's happening is [3,1,4,8,2,1,0] returns a list, not an ndarray. So, the expression ar == 8 returns a scalar False, because all comparisons between list and scalar types return False. Thus, np.where(False) returns an empty array. The way to fix this is:

arr = np.array([3,1,4,8,2,1,0])
np.where(arr == 8)

This returns (array([3]),). There's opportunity for further confusion, because where returns a tuple. If you write a script that intends to access the index position (3, in this case), you need np.where(arr == 8)[0] to pull the first (and only) result out of the tuple. To actually get the value 3, you need np.where(arr == 8)[0][0] (although this will raise an IndexError if there are no 8's in the array).

This is an example where numeric-specialized languages like Matlab or Octave are simpler to use for purely numerical applications, because the language is less general and so has fewer return types to understand.

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

1 Comment

"Matlab or Octave are simpler to use for newbies". No, they just have a simpler syntax for this, no matter the user's level of experience. There is no need to be condescending towards other languages here.

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.