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

by | Programming, Python, Tips

If you try to evaluate a numpy array in the Boolean context, you will raise the error: Python ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all().

To solve this error, you can use the built-in any() and all() functions or the numpy functions logical_and() and logical_or().

This tutorial will go through the error in detail with the help of code examples.


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

What is a ValueError?

In Python, a value is the information stored within a particular object. You will encounter a ValueError in Python when you use a built-in operation or function that receives an argument with the right type but an inappropriate value.

Evaluating a NumPy Array in the Boolean Context

To explain this particular valueerror, consider the code example below:

import numpy as np
star_wars_arr = np.array(["Luke", "Han", "Anakin"])
bool(star_wars_arr)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
      3 star_wars_arr = np.array(["Luke", "Han", "Anakin"])
      4 
      5 bool(star_wars_arr)
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

The error occurs because the numpy array has more than one element.

There are several ways to evaluate this array in the boolean context, for example:

  • It could mean True if any element is True,
  • It could mean True if all elements are true,
  • It could mean True if the array has non-zero length.

Instead of guessing which condition we want to satisfy, the interpreter throws a ValueError.

Example

Let’s look at an example that will raise the ValueError. Consider a numpy array with integer values representing ages in years.

import numpy as np

ages = np.array([7, 19, 20, 35, 10, 42, 8])

We can evaluate single values in the array in the boolean context. For example:

print(ages[0] < 18 and ages[1] > 18)
True

This evaluates to True because 7 is less than 18 and 19 is greater than 18. However, if we try to evaluate multiple elements in the boolean context, we will throw the ValueError. For example:

print(ages[0:3] < 18 and ages[4:6] > 18)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
1 print(ages[0:3] < 18 and ages[4:6] > 18)

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

The error occurs because instead of evaluating single vales, we are evaluating slices of the array. Slices contain more than one element, therefore there is ambiguity in how to determine if the condition is true or not.

Solution

Using any() and all()

Python provides built-in functions any() and all(). The function any() returns True if at least one element satisfies the condition. The function all() returns True if all the elements satisfy the condition. Let’s look at the revised code with any():

print((ages[0:3] < 18).any() and (ages[4:6] > 18).any())

In the above code, we use the any() function to check if any of the elements at the indices from 0 to 2 are less than 18 and if any of the elements at the indices from 4 to 5 are greater than 18. Let’s run the code to see what happens:

True

There is at least one element in each slice that satisfies the given conditions.

Let’s look at the revised code with all():

print((ages[0:3] < 18).all() and (ages[4:6] > 18).all())

In the above code, we use the all() function to check if all of the elements at the indices from 0 to 3 are less than 18 and if all of the elements at the indices from 4 to 6 are greater than 18. Let’s run the code to see what happens:

False

We do not satisfy either of the conditions with the slices of the array.

Using numpy.logical_and() and numpy.logical_or()

We can also use NumPy’s logical functions logical_and and logical_or to find the truth values of two arrays element by element. To use the logical functions, the arrays must be of the same shape. Let’s look at an example of the logical_and() to evaluate two arrays:

import numpy as np

ages = np.array([7, 19, 20, 35, 10, 42, 8])

truth_values_1 = ages[0:2] < 18

print('truth values of first slice: ' , truth_values_1)

truth_values_2 = ages[4:6] > 18

print('truth values of second slice: ' , truth_values_2)

print(np.logical_and(truth_values_1, truth_values_2))

In the above code, we define two arrays of boolean using truth value testing on our array slices and pass them to the logical_and() function. The function checks element by element if both values in each array are True or not. Let’s run the code to get the result:

truth values of first slice:  [ True False]
truth values of second slice:  [False  True]
[False False]

The function returns [False False] because we did not satisfy both conditions at the two specified indices of each array.

Let’s look at an example of the logical_or() to evaluate two arrays

import numpy as np

ages = np.array([7, 19, 20, 35, 10, 42, 8])

truth_values_1 = ages[0:2] < 18

print('truth values of first slice: ' , truth_values_1)

truth_values_2 = ages[4:6] > 18

print('truth values of second slice: ' , truth_values_2)

print(np.logical_or(truth_values_1, truth_values_2))

In the above code, we define two arrays of boolean values using truth value testing on our array slices and pass them to the logical_or() function. The function checks element by element if either value in the arrays is True or not. Let’s run the code to get the result:

truth values of first slice:  [ True False]
truth values of second slice:  [False  True]
[ True  True]

The function returns [True True] because at least one of the arrays has an element that evaluates to True in both cases.

Summary

Congratulations on reading to the end of this tutorial! You will raise the error: Python ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() if you try to get the truth value of a numpy array with more than one element. To solve this error, you can use the any() function if you want at least one element in the array to return True or the all() function if you want all the elements in the array to return True.

You can use the numpy logical functions logical_and() and logical_or() to do an element-wise truth test between two arrays. The function logical_and() will check if both of the elements in each array return True. The function logical_or() will check if either of the elements in each array returns True.

For further reading on using any() and all(), go to the article:

How to Solve Python AttributeError: ‘bool’ object has no attribute ‘all’.

Go to the online courses page on Python to learn more about coding in Python for data science and machine learning.

Have fun and happy researching!

Profile Picture
Senior Advisor, Data Science | [email protected] | + posts

Suf is a senior advisor in data science with deep expertise in Natural Language Processing, Complex Networks, and Anomaly Detection. Formerly a postdoctoral research fellow, he applied advanced physics techniques to tackle real-world, data-heavy industry challenges. Before that, he was a particle physicist at the ATLAS Experiment of the Large Hadron Collider. Now, he’s focused on bringing more fun and curiosity to the world of science and research online.

Buy Me a Coffee ✨