Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Numpy chain comparison with two predicates

In NumPy, I can generate a boolean array like this:

>>> arr = np.array([1, 2, 1, 2, 3, 6, 9])
>>> arr > 2
array([False, False, False, False,  True,  True,  True], dtype=bool)

How can we chain comparisons together? For example:

>>> 6 > arr > 2
array([False, False, False, False,  True,  False,  False], dtype=bool)

Attempting to do so results in the error message

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

like image 626
user1728853 Avatar asked Jun 12 '13 21:06

user1728853


People also ask

How do I compare values in two NumPy arrays?

Method 1: We generally use the == operator to compare two NumPy arrays to generate a new array object. Call ndarray. all() with the new array object as ndarray to return True if the two NumPy arrays are equivalent.

Does Python allow chained comparison?

In Python, comparisons can be chained. You can write a < x and x < b as a < x < b like in mathematics. This article describes the following contents.

How do you compare two matrices with NumPy?

Comparing Arrays in NumPy The easiest way to compare two NumPy arrays is to: Create a comparison array by calling == between two arrays. Call . all() method for the result array object to check if the elements are True.


1 Answers

AFAIK the closest you can get is to use &, |, and ^:

>>> arr = np.array([1, 2, 1, 2, 3, 6, 9])
>>> (2 < arr) & (arr < 6)
array([False, False, False, False,  True, False, False], dtype=bool)
>>> (2 < arr) | (arr < 6)
array([ True,  True,  True,  True,  True,  True,  True], dtype=bool)
>>> (2 < arr) ^ (arr < 6)
array([ True,  True,  True,  True, False,  True,  True], dtype=bool)

I don't think you'll be able to get a < b < c-style chaining to work.

like image 124
DSM Avatar answered Nov 11 '22 20:11

DSM