numpy.where for 2+ specific values

Question:

Can the numpy.where function be used for more than one specific value?

I can specify a specific value:

>>> x = numpy.arange(5)
>>> numpy.where(x == 2)[0][0]
2

But I would like to do something like the following. It gives an error of course.

>>> numpy.where(x in [3,4])[0][0]
[3,4]

Is there a way to do this without iterating through the list and combining the resulting arrays?

EDIT: I also have a lists of lists of unknown lengths and unknown values so I cannot easily form the parameters of np.where() to search for multiple items. It would be much easier to pass a list.

Asked By: aberger

||

Answers:

You can use the numpy.in1d function with numpy.where:

import numpy
numpy.where(numpy.in1d(x, [2,3]))
# (array([2, 3]),)
Answered By: Psidom

I guess np.in1d might help you, instead:

>>> x = np.arange(5)
>>> np.in1d(x, [3,4])
array([False, False, False,  True,  True], dtype=bool)
>>> np.argwhere(_)
array([[3],
       [4]])
Answered By: wim

If you only need to check for a few values you can:

import numpy as np
x = np.arange(4)

ret_arr = np.where([x == 1, x == 2, x == 4, x == 0])[1]
print "Ret arr = ",ret_arr

Output:

Ret arr =  [1 2 0]
Answered By: mitoRibo
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.