简体   繁体   中英

How to construct logical expression for advanced slicing

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.

You could also try numpy.in1d . Say

>>> 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)
>>> (a == 2) | (a == 1)
array([ True,  True, False, False,  True, False,  True,  True], dtype=bool)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM