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

Question

Asked By – Homunculus Reticulli

Let x be a NumPy array. The following:

(x > 1) and (x < 3)

Gives the error message:

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

How do I fix this?

Now we will see solution for issue: ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()


Answer

If a and b are Boolean NumPy arrays, the & operation returns the elementwise-and of them:

a & b

That returns a Boolean array. To reduce this to a single Boolean value, use either

(a & b).any()

or

(a & b).all()

Note: if a and b are non-Boolean arrays, consider (a - b).any() or (a - b).all() instead.


Rationale

The NumPy developers felt there was no one commonly understood way to evaluate an array in Boolean context: it could mean True if any element is True, or it could mean True if all elements are True, or True if the array has non-zero length, just to name three possibilities.

Since different users might have different needs and different assumptions, the
NumPy developers refused to guess and instead decided to raise a ValueError whenever one tries to evaluate an array in Boolean context. Applying and to two numpy arrays causes the two arrays to be evaluated in Boolean context (by calling __bool__ in Python3 or __nonzero__ in Python2).

This question is answered By – unutbu

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0