Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Numpy equal operator overloading and vectorization: The truth value of a Series is ambiguous

I am getting a confusing numpy error and unexpected behavior about how operation overloading works.

Why does the last line, which consists of two chained equal operations, fail, while the first two lines, which do the same thing with two possible orders as dictated by parentheses, work just fine?

import numpy as np

x = np.array([True, False])

(x == False) == True # Works fine, outputs array([False,  True])
x == (False == True) # Works fine, outputs array([False,  True])

x == False == True  # Throws error

The last line throws the following error:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

This is an interesting demonstration of Python’s multiple-equality checks, and not to do with NumPy broadcasting. The third statement is not equivalent to either of the first two; it’s actually bool(x == False) and bool(False == True). The and operator tries to coerce its arguments into booleans via calls to bool, and its this call on x == False that triggers the ValueError. This is in contrast to the first two lines, where no array is ever coerced via bool; rather, it is just broadcasted comparisons, as you said.

(See the documentation on comparison operator precedence for more information from the actual source.)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading