The error message explains it pretty well:
ValueError: The truth value of an array with more than one element is ambiguous.
Use a.any() or a.all()
What should bool(np.array([False, False, True]))
return? You can make several plausible arguments:
(1) True
, because bool(np.array(x))
should return the same as bool(list(x))
, and non-empty lists are truelike;
(2) True
, because at least one element is True
;
(3) False
, because not all elements are True
;
and that's not even considering the complexity of the N-d case.
So, since "the truth value of an array with more than one element is ambiguous", you should use .any()
or .all()
, for example:
>>> v = np.array([1,2,3]) == np.array([1,2,4])
>>> v
array([ True, True, False], dtype=bool)
>>> v.any()
True
>>> v.all()
False
and you might want to consider np.allclose
if you're comparing arrays of floats:
>>> np.allclose(np.array([1,2,3+1e-8]), np.array([1,2,3]))
True