Skip to content

[Solved][Python] Numpy Erorr: ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

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 is True, return True; otherwise, it will return False.
  • all(): If all elements in the judgment are True, return True; otherwise, return False.
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


Read More

Tags:

Leave a Reply