[Numpy-discussion] Boolean arrays

Brett Olsen brett.olsen@gmail....
Fri Aug 27 14:58:45 CDT 2010


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


More information about the NumPy-Discussion mailing list