[Numpy-discussion] Numpy array in iterable

Kim Hansen slaunger@gmail....
Wed Feb 25 08:02:24 CST 2009


Yes, this is exactly what I was after, only the function name did not
ring a bell (I still cannot associate it with something meaningful for
my use case). Thanks!

-- Slaunger

2009/2/25  <josef.pktd@gmail.com>:
> On Wed, Feb 25, 2009 at 7:28 AM, Kim Hansen <slaunger@gmail.com> wrote:
>> 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
>> _______________________________________________
>> Numpy-discussion mailing list
>> Numpy-discussion@scipy.org
>> http://projects.scipy.org/mailman/listinfo/numpy-discussion
>>
>
> does this help:
>
>>>> np.setmember1d(test,states)
> array([ True, False,  True, False, False], dtype=bool)
>
> Josef
> _______________________________________________
> Numpy-discussion mailing list
> Numpy-discussion@scipy.org
> http://projects.scipy.org/mailman/listinfo/numpy-discussion
>


More information about the Numpy-discussion mailing list