[Numpy-discussion] where construct
Christopher Barker
Chris.Barker at noaa.gov
Thu Dec 20 13:21:29 EST 2007
Hans Meine wrote:
>> where( (a<1 or b<3), b,c)
>
> Now + and | have been proposed to you, but it looks to me as if the "correct
> way" would be logical_or. All solutions give the same result, but logical_or
> better expresses what you're trying to do:
>
> In [9]: print where( (logical_or(a<1, b<3)), b,c)
> [4 2 2 1]
> (Think of the Zen.)
I'm not sure the Zen answers this one for us. It's really a matter of
taste, and many of us prefer infix notation for this kind of thing. I think:
where( ( (a<1) | (b<3) ), b,c)
reads better than:
where( (logical_or(a<1, b<3)), b,c)
The only reason we need to use "|" (which means logical_or for boolean
arrays) rather than "or" is that we can't overload the python "or" or
"and" because they are designed to short-circuit. If you want to be
really explicit, you could do:
where( (logical_or(less(a,1), less(b,3))), b,c)
or, since I like to use namespaces (also see the Zen):
import numpy as N
N.where( (N.logical_or(N.less(a,1), N.less(b,3))), b,c)
which are even harder to read.
-Chris
--
Christopher Barker, Ph.D.
Oceanographer
Emergency Response Division
NOAA/NOS/OR&R (206) 526-6959 voice
7600 Sand Point Way NE (206) 526-6329 fax
Seattle, WA 98115 (206) 526-6317 main reception
Chris.Barker at noaa.gov
More information about the NumPy-Discussion
mailing list