-2

The fastest way to find numbers indexes in np. array in Python is?

Suppose we have a list of numbers from 0 to 20, and we want to know the indexes of digits 2 and 5

2

1 Answer 1

1

The canonical way would be to use numpy's where method:

a = np.array(range(20))
np.where((a == 2) | (a == 5))

Note that in order to combine the two terms (a == 2) and (a == 5) we need the bitwise or operator |. The reason is that both (a == 2) and (a == 5) return a numpy array of dtype('bool'):

>>> a == 2
array([False, False,  True, False, False, False, False, False, False,
       False, False, False, False, False, False, False, False, False,
       False, False])

>>> (a == 5)
array([False, False, False, False, False,  True, False, False, False,
       False, False, False, False, False, False, False, False, False,
       False, False])

>>> (a == 2) | (a==5)
array([False, False,  True, False, False,  True, False, False, False,
       False, False, False, False, False, False, False, False, False,
       False, False])

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.