[Numpy-discussion] Numpy array in iterable

Kim Hansen slaunger at gmail.com
Wed Feb 25 07:28:26 EST 2009


Hi Numpy discussions
Quite often I find myself wanting to generate a boolean mask for fancy
slicing of some array, where the mask itself is generated by checking
if its value has one of several relevant values (corresponding to
states)
So at the the element level thsi corresponds to checking if
element in iterable
But I can't use the in operator on a numpy array:

In [1]: test = arange(5)
In [2]: states = [0, 2]
In [3]: mask = test in states
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
C:\Documents and Settings\kha\<ipython console> in <module>()
ValueError: The truth value of an array with more than one element is ambiguous.
Use a.any() or a.all()

I can however make my own utility function which works effectively the
same way by iterating through the states

In [4]: for i, state in enumerate(states):
  ...:     if i == 0:
  ...:         result = test == state
  ...:     else:
  ...:         result |= test == state
  ...:
  ...:
In [5]: result
Out[5]: array([ True, False,  True, False, False], dtype=bool)

However, I would have thought such an "array.is_in()" utility function
was already available in the numpy package?

But I can't find it, and I am curious to hear if it is there or if it
just available in another form which I have simply overlooked.

If it is not there I think it could be a nice extra utility funtion
for the ndarray object.

--Slaunger



More information about the NumPy-Discussion mailing list