1

I am trying to figure out a cleaner way of doing the following:

import numpy

a = np.array([1,2,4,5,1,4,2,1])

cut = a == (1 or 2)
print cut

[ True False False False  True False False  True]

The above is of course a simplified example. The expression (1 or 2) can be large or complicated. As a start, I would like to generalize this thusly:

cutexp = (1 or 2)
cut = a == cutexp

Maybe, cutexp can be turned into a function or something but I'm not sure where to start looking.

4

2 回答 2

3

您也可以尝试numpy.in1d。说

>>> a = np.array([1,2,4,5,1,4,2,1])
>>> b = np.array([1,2]) # Your test array
>>> np.in1d(a,b)
array([ True,  True, False, False,  True, False,  True,  True], dtype=bool)
于 2012-05-05T18:49:57.183 回答
2
>>> (a == 2) | (a == 1)
array([ True,  True, False, False,  True, False,  True,  True], dtype=bool)
于 2012-05-05T18:45:03.357 回答