Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't chained (interval) comparison work on numpy arrays?

a < b < c is an chained expression in Python, and it looks like it works on objects with appropriate comparison operators defined, but it doesn't work on numpy arrays. Why?

import numpy as np

class ContrarianContainer(object):
    def __init__(self, x):
        self.x = x
    def __le__(self, y):
        return not self.x <= y
    def __lt__(self, y):
        return not self.x < y
    def __ge__(self, y):
        return not self.x >= y
    def __gt__(self, y):
        return not self.x > y
    def __eq__(self, y):
        return not self.x == y
    def __ne__(self, y):
        return not self.x != y

numlist = np.array([1,2,3,4])
for n in numlist:
    print 0 < n < 3.5
for n in numlist:
    print 0 > ContrarianContainer(n) > 3.5
print 0 < numlist < 3.5

this prints:

True
True
True
False
True
True
True
False
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-187-277da7750148> in <module>()
      4 for n in numlist:
      5     print 0 < n < 3.5
----> 6 print 0 < numlist < 3.5

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
like image 734
Jason S Avatar asked Feb 20 '17 22:02

Jason S


1 Answers

0 < numlist < 3.5

Is equivalent to:

(0 < numlist) and (numlist < 3.5)

except that numlist is only evaluated once.

The implicit and between the two results is causing the error

like image 97
John La Rooy Avatar answered Sep 21 '22 20:09

John La Rooy