# [Numpy-discussion] Boolean arrays

Ken Watford kwatford+scipy@gmail....
Fri Aug 27 15:10:06 CDT 2010

On Fri, Aug 27, 2010 at 3:58 PM, Brett Olsen <brett.olsen@gmail.com> wrote:
> Hello,
>
> I have an array of non-numeric data, and I want to create a boolean
> array denoting whether each element in this array is a "valid" value
> or not.  This is straightforward if there's only one possible valid
> value:
>>>> import numpy as N
>>>> ar = N.array(("a", "b", "c", "b", "b", "a", "d", "c", "a"))
>>>> ar == "a"
> array([ True, False, False, False, False,  True, False, False,  True],
> dtype=bool)
>
> If there's multiple possible valid values, I've come up with a couple
> possible methods, but they all seem to be inefficient or kludges:
>>>> valid = N.array(("a", "c"))
>>>> (ar == valid[0]) | (ar == valid[1])
> array([ True, False,  True, False, False,  True, False,  True,  True],
> dtype=bool)
>>>> N.array(map(lambda x: x in valid, ar))
> array([ True, False,  True, False, False,  True, False,  True,  True],
> dtype=bool)
>
> Is there a numpy-appropriate way to do this?
>
> Thanks,
> Brett Olsen

amap: Like Map, but for arrays.

>>> ar = numpy.array(("a", "b", "c", "b", "b", "a", "d", "c", "a"))
>>> valid = ('a', 'c')
>>> numpy.amap(lambda x: x in valid, ar)
array([ True, False,  True, False, False,  True, False,  True,  True],
dtype=bool)