Why comparison of chains (intervals) doesn't work on numpy arrays?

a < b < cis a chained expression in Python, and it looks like it works with objects with the appropriate comparison operators defined, but it doesn’t work with 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()
+4
source share
2 answers
0 < numlist < 3.5

It is equivalent to:

(0 < numlist) and (numlist < 3.5)

except that it numlistis evaluated only once.

Implicit andbetween two results causes an error

+6
source

So the docs say:

, a, b, c,..., y, z op1, op2,..., opN , op1 b op2 c... y opN z a op1 b b op2 c ... y opN z, , .

( z , x < y ).

In [20]: x=5
In [21]: 0<x<10
Out[21]: True
In [22]: 0<x and x<10
Out[22]: True

In [24]: x=np.array([4,5,6])    
In [25]: 0<x and x<10
...
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

ValueError , , , numpy.

In [26]: (0<x)
Out[26]: array([ True,  True,  True], dtype=bool)

In [30]: np.array([True, False]) or True
...
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
In [33]: if np.array([True, False]): print('yes')
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

0<x, x<10, or/and. numpy | &, or and.

In [34]: (0<x) & x<10
Out[34]: array([ True,  True,  True], dtype=bool)

0 < x <10, .

In [35]: f = np.vectorize(lambda x: 0<x<10, otypes=[bool])
In [36]: f(x)
Out[36]: array([ True,  True,  True], dtype=bool)
In [37]: f([-1,5,11])
Out[37]: array([False,  True, False], dtype=bool)

, <:

In [39]: 0 < [-1,5,11]
TypeError: unorderable types: int() < list()

, & <:

In [44]: 0 < x & x<10
ValueError ...

In [45]: (0 < x) & x<10
Out[45]: array([ True,  True,  True], dtype=bool)

In [46]: 0 < x & (x<10)
Out[46]: array([False,  True, False], dtype=bool)

In [47]: 0 < (x & x)<10
ValueError...

, (0 < x) & (x<10), , < &.

+2

Source: https://habr.com/ru/post/1670347/


All Articles