numpy.where() and multiple comparisons

Tim Roberts timr at probo.com
Sat Jan 18 16:20:54 EST 2014


Peter Otten <__peter__ at web.de> wrote:

>John Ladasky wrote:
>
>> On Friday, January 17, 2014 6:16:28 PM UTC-8, duncan smith wrote:
>> 
>>>  >>> a = np.arange(10)
>>>  >>> c = np.where((2 < a) & (a < 7))
>>>  >>> c
>>> (array([3, 4, 5, 6]),)
>> 
>> Nice!  Thanks!
>> 
>> Now, why does the multiple comparison fail, if you happen to know?
>
>2 < a < 7
>
>is equivalent to
>
>2 < a and a < 7
>
>Unlike `&` `and` cannot be overridden (*),,,,

And just in case it isn't obvious to the original poster, the expression "2
< a" only works because the numpy.array class has an override for the "<"
operator.  Python natively has no idea how to compare an integer to a
numpy.array object.

Similarly, (2 < a) & (a > 7) works because numpy.array has an override for
the "&" operator.  So, that expression is compiled as

    numpy.array.__and__(
        numpy.array.__lt__(2, a),
        numpy.array.__lt__(a, 7)
    )

As Peter said, there's no way to override the "and" operator.
-- 
Tim Roberts, timr at probo.com
Providenza & Boekelheide, Inc.



More information about the Python-list mailing list