[Numpy-discussion] ndarray with double comparison
Benjamin Root
ben.root@ou....
Thu Oct 13 11:22:03 CDT 2011
On Thu, Oct 13, 2011 at 11:13 AM, Chao YUE <chaoyuejoy@gmail.com> wrote:
> Dear all,
>
> sorry for this stupid question but I cannot find it in numpy tutorial or
> google.
> suppose I have a=np.arange(11).
>
> In [32]: a < 8
> Out[32]:
> array([ True, True, True, True, True, True, True, True, False,
> False, False], dtype=bool)
>
> In [34]: a > 4
> Out[34]:
> array([False, False, False, False, False, True, True, True, True,
> True, True], dtype=bool)
>
> how can I have boolean index like 4 < a < 8
> np.where(a>4 and a<8);or plainly input "a>4 and a<8" doesn't work.
>
> thanks,
>
> Chao
>
>
Unfortunately, you can't use "and", "or", "not" keywords with boolean arrays
because numpy can't overload them. Instead, use the bitwise operators: '&',
'|', and '~'. Be careful, though, because of operator precedence is
different for bitwise operators than the boolean keywords. I am in the
habit of always wrapping my boolean expressions in parentheses, just in
case.
(a > 4) & (a < 8)
is what you want. Note that "a > 4 & a < 8" would be evaluated in a
different order -- "4 & a" would be first.
I hope that helps!
Ben Root
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.scipy.org/pipermail/numpy-discussion/attachments/20111013/1fbbdd59/attachment.html
More information about the NumPy-Discussion
mailing list