1

I have a numpy array: k = np.array([100,20,25,10,1,2]) and I'm trying to use a np where as index=np.where(k<10) which gives me index (array([4, 5]),). I'm insterested in something to give me just the index so here I'd like to have index[0]=4 not index[0]=[4 5]

I couldn't find anything here on the numpy docs.

3
  • 4
    There are two elements <10; therefore two indices. Commented Jul 12, 2017 at 22:37
  • 3
    I believe you can change index = np.where(k<10) to index = np.where(k<10)[0] to get what you want. Commented Jul 12, 2017 at 22:41
  • 2
    It sounds like you may be confused by the fact that where returns a tuple of arrays of indices, instead of just an array of indices. Commented Jul 12, 2017 at 22:45

2 Answers 2

4

You can take the first element in the result that you get, as follows:

index=np.where(k<10)[0]

Then index is array([4, 5], dtype=int64), and you can access index[0] and index[1] as you wanted.

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

Comments

1

You can use numpy.flatnonzero, which returns an array of index instead of tuples of array(s):

k = np.array([100,20,25,10,1,2])

np.flatnonzero(k < 10)
# array([4, 5])

4 Comments

This does the exact same thing as what the OP did not want, and just uses a (relatively) obscure method to do so.
@AlexanderHuszagh I am not so sure. This does give the same output as numpy.where but for 1d array, it has the convenience of returning an array of non zero elements index, instead of a tuple.
@AlexanderHuszagh works for me as I understand the OP's desire, but also completely non-obvious as a method to get those results.
@Psidom, the user clearly wants an element from the where tuple. This could either be flatnonzero(cond)[0], or where(cond)[0][0], or some other index.

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.