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?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
If
aandbare Boolean NumPy arrays, the&operation returns the elementwise-and of them:That returns a Boolean array. To reduce this to a single Boolean value, use either
or
Note: if
aandbare 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
Trueif any element isTrue, or it could meanTrueif all elements areTrue, orTrueif 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
ValueErrorwhenever one tries to evaluate an array in Boolean context. Applyingandto two numpy arrays causes the two arrays to be evaluated in Boolean context (by calling__bool__in Python3 or__nonzero__in Python2).