Arithmetic comparisons on numpy arrays

>>> import numpy as np >>> x = np.eye(3) >>> x[1, 2] = .5 >>> x array([[ 1. , 0. , 0. ], [ 0. , 1. , 0.5], [ 0. , 0. , 1. ]]) >>> 0 < x.any() < 1 False >>> 

I would like to check if the numpy array contains any value between 0 and 1.
I read 0 < x.any() < 1 as "if there is any element larger than 0 and less than 1, return true", but this is obviously not the case.

How can I do arithmetic comparison in a numpy array?

+4
source share
2 answers
 >>> np.any((0 < x) & (x < 1)) True 

What x.any() really does: this is the same as np.any(x) , i.e. returns True if any elements from x are nonzero. So, your comparison is 0 < True < 1 , which is wrong, because in python 2 0 < True true, but True < 1 not, since True == 1 .

In this approach, in contrast, we create logical arrays of whether the comparison is true for each element, and then check whether any element of this array is true:

 >>> 0 < x array([[ True, False, False], [False, True, True], [False, False, True]], dtype=bool) >>> x < 1 array([[False, True, True], [ True, False, True], [ True, True, False]], dtype=bool) >>> (0 < x) & (x < 1) array([[False, False, False], [False, False, True], [False, False, False]], dtype=bool) 

You have to do explicit & , because, unfortunately, numpy does not (and I think I can not) work with the built-in chain of python operators of comparison operators.

+2
source

The first tests are x.any() code, which evaluates to True because x contains a nonzero value. Then it tests 0 < True (=1) < 1 , which is False . At:

 ((0 < x) & (x < 1)).any() 
+1
source

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


All Articles