user2136786
user2136786

Reputation: 305

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 numpy array contains any value between 0 and 1.
I read 0 < x.any() < 1 as 'if there is any element with size greater then 0 and less then 1, return true', but that's obviously not the case.

How can I do arithmetic comparison on numpy array?

Upvotes: 4

Views: 583

Answers (2)

shx2
shx2

Reputation: 64328

Your code first tests x.any(), which evaluates to True, as x includes a nonzero value. It then tests 0 < True (=1) < 1, which is False. Do:

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

Upvotes: 1

Danica
Danica

Reputation: 28846

>>> np.any((0 < x) & (x < 1))
True

What x.any() actually does: it's the same as np.any(x), meaning it returns True if any elements in x are nonzero. So your comparison is 0 < True < 1, which is false because in python 2 0 < True is true, but True < 1 is not, since True == 1.

In this approach, by contrast, we make boolean arrays of whether the comparison is true for each element, and then check if any element of that 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 the explicit &, because unfortunately numpy doesn't (and I think can't) work with python's built-in chaining of comparison operators.

Upvotes: 2

Related Questions