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

Last Updated On
Monday 23rd May 2022

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

For boolean arrays – and comparisons like <, <=, ==, !=, >= and > on NumPy arrays return boolean NumPy arrays – you can also use the element-wise bitwise functions (and operators): np.bitwise_and (& operator)

	import numpy as np
first = np.array([1, 2, 3])
second = bool(first)
print(second)
	

The output will be this error message:

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

The element-wise equivalent for and would be the np.logical_and function, similarly you could use np.logical_or as equivalent for or.

Logical_and() function

	import numpy as np
arr = np.array([1, 2, 3])
print(np.logical_and(arr > 1, arr < 3))
	
	[False  True False]
	

Logical_or() function

	import numpy as np
arr1 = np.arange(5)
arr2 = np.arange(5, 10)
arr3 = np.array(['First', 'Second', 'Third', 'Fourth', 'Fifth'])
mask = np.logical_or(arr1 >= 3, arr2 < 3)
print(arr3[mask])
	
	['Fourth' 'Fifth']
	
	import numpy as np
np1 = np.zeros((3,))
np2 = np.ones((3,))
np1 in (np1, np2) # True
	

The Truth Value of an array with more than one element is ambiguous.

	np1 in (np2, np1)

ValueError   Traceback (most recent call last)
<gfd.py> in <module> 1 np1 in (np2, np1)

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

array([ True,  True,  True])

np1 is np1 or np1 == np1 # True

np1 is np2 or np1 == np2 # False
	
	any(np1 is e or np1 == e for e in (np2, np1)

ValueError    Traceback (most recent call last)
<gfd.py> in <module> 1 any(np1 is e or np1 == e for e in (np2, np1))

ValueError: The truth value of an array with more than one element is ambiguous. Use `a.any()` or `a.all()`.The issue does not occur when == is never broadcasted.
	
	np1 in (np3, np1) # True