Last Updated on 2021-10-30 by Clay
When using Numpy format data for conditional judgment, sometimes we get the following error message:
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
This is because if we want to determine whether the data in Numpy format is congruent, the method does not fit the expectations of Numpy design.
Error Example
The possible reasons for this error message are from the following syntax:
import numpy as np
arr = np.array([1, 2, 3])
if (arr == [1, 2, 3]):
print("ok")
Output:
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
In fact, if you print out the content of the judgment, the data in Numpy format is actually judged for each element.
import numpy as np
arr = np.array([1, 2, 3])
print(arr == [1, 2, 3])
Output:
[ True True True]
Therefore, it does not constitute a condition put into the if
judgment formula at all.
Solution
We need to judge through any()
and all()
methods in Numpy.
any()
: If any element in the judgment isTrue
, returnTrue
; otherwise, it will returnFalse
.all()
: If all elements in the judgment areTrue
, returnTrue
; otherwise, returnFalse
.
import numpy as np
print((np.array([1, 2, 3]) == [1, 2, 4]).all())
print((np.array([1, 2, 3]) == [1, 2, 4]).any())
Output:
False
True
References
- https://stackoverflow.com/questions/10062954/valueerror-the-truth-value-of-an-array-with-more-than-one-element-is-ambiguous
- https://blog.finxter.com/how-to-fix-valueerror-the-truth-value-of-an-array-with-more-than-one-element-is-ambiguous-use-a-any-or-a-all/
Read More
- [Solved] FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. _np_qint8 = np.dtype([("qint8", np.int8, 1)])
- [Python] How To Convert Numpy Data Format To Tuple Or List
- [Python] Convert the value to one-hot type in Numpy