Unexpected behavior of boolean operations in NumPy ndarray inline comparisons - python

I find that attempting to perform multiple boolean comparisons on numpy ndarrays using &, |, ==, >=, etc. often gives unexpected results, where the pure python order of operations seems on the surface to be violated (I was wrong about this; for example, True | False==True yields True). What are the "rules" or things going on under the hood that explain these results? Here are a few examples:
Comparing a boolean ndarray to the results of an elementwise comparison on a non-boolean ndarray:
In [36]: a = np.array([1,2,3])
In [37]: b = np.array([False, True, False])
In [38]: b & a==2 # unexpected, with no error raised!
Out[38]: array([False, False, False], dtype=bool)
In [39]: b & (a==2) # enclosing in parentheses resolves this
Out[39]: array([False, True, False], dtype=bool)
Elementwise &/| on boolean and non-boolean ndarrays:
In [79]: b = np.array([True,False,True])
In [80]: b & a # comparison is made, then array is re-cast into integers!
Out[80]: array([1, 0, 1])
Finding elements of array within two values:
In [47]: a>=2 & a<=2 # have seen this in different stackexchange threads
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
In [48]: (a>=2) & a<=2 # similar to behavior in In[38], but instead get *True* boolean array of
Out[48]: array([ True, True, True], dtype=bool)
In [49]: (a>=2) & (a<=2) # expected results
Out[49]: array([False, True, False], dtype=bool)
Logical &/| yielding results not in or [0,1] (which would be expected if a boolean result was coerced back into int).
In [90]: a & 2
Out[90]: array([0, 2, 2])
I welcome additional examples of this behavior.

I think you are confused about the precedence of the & | binary operators vs the comparison operators:
>>> import dis
>>> dis.dis("b & a==2")
1 0 LOAD_NAME 0 (b)
2 LOAD_NAME 1 (a)
4 BINARY_AND
6 LOAD_CONST 0 (2)
8 COMPARE_OP 2 (==)
10 RETURN_VALUE
You can see here that BINARY_AND is done first (between b and a) then the result is compared against 2 which, since it is a boolean array, is all False
The reason & and | have lower precedence is because they are not intended as logical operators, it represents the binary (math?) operation which numpy happens to use for logic, for example with ints I'd definitely expect the & to happen first:
if 13 & 7 == 5:
It is unfortunate that numpy cannot override the behaviour of the logical and and or operators since their precedence makes sense as logical operators but unfortunately they cannot be overridden so we just have to live will adding lots of brackets when doing boolean arrays.
Note that there was a proposal to allow and or to be overloaded but was not passed since basically it would only be a small convinience for numpy while making all other strict boolean operations slower.

a>=2 & a<=2 is evaluated as a>=(2 & a)<=2
The () part evaluates to array([0, 0, 2], dtype=int32)
a>=(2 & a) is a boolean array. But it is part of a Python a<x<b expression, which internally uses short circuiting. That is, it evaluates a<x and depending its value might actually skip the <b part. Something like True if a<x else x<b.
The familiar ValueError ambiguous arises when a boolean array is used in a scalar Python boolean context.

Related

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() (couldnt figure out the solution) [duplicate]

Let x be a NumPy array. The following:
(x > 1) and (x < 3)
Gives the error message:
ValueError: The truth value of an array with more than one element is
ambiguous. Use a.any() or a.all()
How do I fix this?
If a and b are Boolean NumPy arrays, the & operation returns the elementwise-and of them:
a & b
That returns a Boolean array. To reduce this to a single Boolean value, use either
(a & b).any()
or
(a & b).all()
Note: if a and b are non-Boolean arrays, consider (a - b).any() or (a - b).all() instead.
Rationale
The NumPy developers felt there was no one commonly understood way to evaluate an array in Boolean context: it could mean True if any element is True, or it could mean True if all elements are True, or True if the array has non-zero length, just to name three possibilities.
Since different users might have different needs and different assumptions, the
NumPy developers refused to guess and instead decided to raise a ValueError whenever one tries to evaluate an array in Boolean context. Applying and to two numpy arrays causes the two arrays to be evaluated in Boolean context (by calling __bool__ in Python3 or __nonzero__ in Python2).
I had the same problem (i.e. indexing with multi-conditions, here it's finding data in a certain date range). The (a-b).any() or (a-b).all() seem not working, at least for me.
Alternatively I found another solution which works perfectly for my desired functionality (The truth value of an array with more than one element is ambigous when trying to index an array).
Instead of using suggested code above, use:
numpy.logical_and(a, b)
The reason for the exception is that and implicitly calls bool. First on the left operand and (if the left operand is True) then on the right operand. So x and y is equivalent to bool(x) and bool(y).
However the bool on a numpy.ndarray (if it contains more than one element) will throw the exception you have seen:
>>> import numpy as np
>>> arr = np.array([1, 2, 3])
>>> bool(arr)
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
The bool() call is implicit in and, but also in if, while, or, so any of the following examples will also fail:
>>> arr and arr
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
>>> if arr: pass
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
>>> while arr: pass
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
>>> arr or arr
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
There are more functions and statements in Python that hide bool calls, for example 2 < x < 10 is just another way of writing 2 < x and x < 10. And the and will call bool: bool(2 < x) and bool(x < 10).
The element-wise equivalent for and would be the np.logical_and function, similarly you could use np.logical_or as equivalent for or.
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)
>>> np.logical_and(arr > 1, arr < 3)
array([False, True, False], dtype=bool)
>>> np.bitwise_and(arr > 1, arr < 3)
array([False, True, False], dtype=bool)
>>> (arr > 1) & (arr < 3)
array([False, True, False], dtype=bool)
and bitwise_or (| operator):
>>> np.logical_or(arr <= 1, arr >= 3)
array([ True, False, True], dtype=bool)
>>> np.bitwise_or(arr <= 1, arr >= 3)
array([ True, False, True], dtype=bool)
>>> (arr <= 1) | (arr >= 3)
array([ True, False, True], dtype=bool)
A complete list of logical and binary functions can be found in the NumPy documentation:
"Logic functions"
"Binary operations"
if you work with pandas what solved the issue for me was that i was trying to do calculations when I had NA values, the solution was to run:
df = df.dropna()
And after that the calculation that failed.
Taking up #ZF007's answer, this is not answering your question as a whole, but can be the solution for the same error. I post it here since I have not found a direct solution as an answer to this error message elsewhere on Stack Overflow.
The error, among others, appears when you check whether an array was empty or not.
if np.array([1,2]): print(1) --> ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all().
if np.array([1,2])[0]: print(1) --> no ValueError, but: if np.array([])[0]: print(1) --> IndexError: index 0 is out of bounds for axis 0 with size 0.
if np.array([1]): print(1) --> no ValueError, but again will not help at an array with many elements.
if np.array([]): print(1) --> DeprecationWarning: The truth value of an empty array is ambiguous. Returning False, but in future this will result in an error. Use 'array.size > 0' to check that an array is not empty.
if np.array([]).size is not None: print(1): Taking up a comment by this user, this does not work either. This is since no np.array can ever be the same object as None - that object is unique - and thus will always match is not None (i.e. never match is None) whether or not it's empty.
Doing so:
if np.array([]).size: print(1) solved the error.
This typed error-message also shows while an if-statement comparison is done where there is an array and for example a bool or int. See for example:
... code snippet ...
if dataset == bool:
....
... code snippet ...
This clause has dataset as array and bool is euhm the "open door"... True or False.
In case the function is wrapped within a try-statement you will receive with except Exception as error: the message without its error-type:
The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
Normally, when you compare two single digits the Python regular codes work correctly, but inside an array there are some digits (more than one number) that should be processed in parallel.
For example, let us assume the following:
a = np.array([1, 2, 3])
b = np.array([2, 3, 4])
And you want to check if b >= a: ?
Because, a and b are not single digits and you actually mean if every element of b is greater than the similar number in a, then you should use the following command:
if (b >= a).all():
print("b is greater than a!")
Cause
This error occurs any time that the code attempts to convert a Numpy array to boolean (i.e., to check its truth value, as described in the error message). For a given array a, this can occur:
Explicitly, by using bool(a).
Implicitly with boolean logical operators: a and a, a or a, not a.
Implicitly using the built-in any and all functions. (These can accept a single array, regardless of how many dimensions it has; but cannot accept a list, tuple, set etc. of arrays.)
Implicitly in an if statement, using if a:. While it's normally possible to use any Python object in an if statement, Numpy arrays deliberately break this feature, because it could easily be used to write incorrect code by mistake otherwise.
Numpy arrays and comparisons (==, !=, <, >, <=, >=)
Comparisons have a special meaning for Numpy arrays. We will consider the == operator here; the rest behave analogously. Suppose we have
import numpy as np
>>> a = np.arange(9)
>>> b = a % 3
>>> a
array([0, 1, 2, 3, 4, 5, 6, 7, 8])
>>> b
array([0, 1, 2, 0, 1, 2, 0, 1, 2])
Then, a == b does not mean "give a True or False answer: is a equal to b?", like it would usually mean. Instead, it will compare the values element by element, and evaluate to an array of boolean results for those comparisons:
>>> a == b
array([ True, True, True, False, False, False, False, False, False])
In other words, it does the same kind of broadcasting that mathematical operators (like b = a % 3) do.
It does not make sense to use this result for an if statement, because it is not clear what to do: should we enter the if block, because some of the values matched? Or should we enter the else block, because some of the values didn't match? Here, Numpy applies an important principle from the Zen of Python: "In the face of ambiguity, refuse the temptation to guess."
Thus, Numpy will only allow the array to be converted to bool, if it contains exactly one element. (In some older versions, it will also convert to False for an empty array; but there are good logical reasons why this should also be treated as ambiguous.)
Similarly, comparing a == 4 will not check whether the array is equal to the integer (of course, no array can ever be equal to any integer). Instead, it will broadcast the comparison across the array, giving a similar array of results:
>>> a == 4
array([False, False, False, False, True, False, False, False, False])
Fixing expressions
If the code is explicitly converting to bool, choose between applying .any or .all to the result, as appropriate. As the names suggest, .any will collapse the array to a single boolean, indicating whether any value was truthy; .all will check whether all values were truthy.
>>> (a == 4).all() # `a == 4` contains some `False` values
False
>>> (a == 4).any() # and also some `True` values
True
>>> a.all() # We can check `a` directly as well: `0` is not truthy,
False
>>> a.any() # but other values in `a` are.
True
If the goal is to convert a to boolean element-wise, use a.astype(bool), or (only for numeric inputs) a != 0.
If the code is using boolean logic (and/or/not), use bitwise operators (&/|/~, respectively) instead:
>>> ((a % 2) != 0) & ((a % 3) != 0) # N.B. `&`, not `and`
array([False, True, False, False, False, True, False, True, False])
Note that bitwise operators also offer access to ^ for an exclusive-or of the boolean inputs; this is not supported by logical operators (there is no xor).
For a list (or other sequence) of arrays that need to be combined in the same way (i.e., what the built-ins all and any do), instead build the corresponding (N+1)-dimensional array, and use np.all or np.any along axis 0:
>>> a = np.arange(100) # a larger array for a more complex calculation
>>> sieves = [a % p for p in (2, 3, 5, 7)]
>>> all(sieves) # won't work
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: The truth value of an array with more than one element is ambiguous.
Use a.any() or a.all()
>>> np.all(np.array(sieves), axis=0) # instead:
array([False, True, False, False, False, False, False, False, False,
False, False, True, False, True, False, False, False, True,
False, True, False, False, False, True, False, False, False,
False, False, True, False, True, False, False, False, False,
False, True, False, False, False, True, False, True, False,
False, False, True, False, False, False, False, False, True,
False, False, False, False, False, True, False, True, False,
False, False, False, False, True, False, False, False, True,
False, True, False, False, False, False, False, True, False,
False, False, True, False, False, False, False, False, True,
False, False, False, False, False, False, False, True, False,
False])
Fixing if statements
First, keep in mind that if the code has an if statement that uses a broken expression (like if (a % 3 == 0) or (a % 5 == 0):), then both things will need to be fixed.
Generally, an explicit conversion to bool (using .all() or .any() as above) will avoid an exception:
>>> a = np.arange(20) # enough to illustrate this
>>> if ((a % 3 == 0) | (a % 5 == 0)).any():
... print('there are fizzbuzz values')
...
there are fizzbuzz values
but it might not do what is wanted:
>>> a = np.arange(20) # enough to illustrate this
>>> if ((a % 3 == 0) | (a % 5 == 0)).any():
... a = -1
...
>>> a
-1
If the goal is to operate on each value where the condition is true, then the natural way to do that is to use the mask as a mask. For example, to assign a new value everywhere the condition is true, simply index into the original array with the computed mask, and assign:
>>> a = np.arange(20)
>>> a[(a % 3 == 0) | (a % 5 == 0)] = -1
>>> a
array([-1, 1, 2, -1, 4, -1, -1, 7, 8, -1, -1, 11, -1, 13, 14, -1, 16,
17, -1, 19])
This indexing technique is also useful for finding values that meet a condition. Building on the previous sieves example:
>>> a = np.arange(100)
>>> sieves = [a % p for p in (2, 3, 5, 7)]
>>> a[np.all(np.array(sieves), axis=0)]
array([ 1, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71,
73, 79, 83, 89, 97])
(Exercise: study the code and understand why this result isn't quite a list of primes under 100; then fix it.)
Using Pandas
The Pandas library has Numpy as a dependency, and implements its DataFrame type on top of Numpy's array type. All the same reasoning applies, such that Pandas Series (and DataFrame) objects cannot be used as boolean: see Truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
The Pandas interface for working around the problem is a bit more complicated - and best understood by reading that Q&A. The question specifically covers Series, but the logic generally applies to DataFrames as well. If you need more specific guidance, though, see If condition with a dataframe.
For me, this error occurred on testing, code with error below:
pixels = []
self.pixels = numpy.arange(1, 10)
self.assertEqual(self.pixels, pixels)
This code returned:
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
Because i cannot assert with a list the object returned by method arrange of numpy.
Solution as transform the arrange object of numpy to list, my choice was using the method toList(), as following:
pixels = []
self.pixels = numpy.arange(1, 10).toList()
self.assertEqual(self.pixels, pixels)
Simplest answer is use "&" instead of "and".
>>> import numpy as np
>>> arr = np.array([1, 4, 2, 7, 5])
>>> arr[(arr > 3) and (arr < 6)] # this will fail
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
>>> arr[(arr > 3) & (arr < 6)] # this will succeed
array([4, 5])

How can I fix this "The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()"? [duplicate]

Let x be a NumPy array. The following:
(x > 1) and (x < 3)
Gives the error message:
ValueError: The truth value of an array with more than one element is
ambiguous. Use a.any() or a.all()
How do I fix this?
If a and b are Boolean NumPy arrays, the & operation returns the elementwise-and of them:
a & b
That returns a Boolean array. To reduce this to a single Boolean value, use either
(a & b).any()
or
(a & b).all()
Note: if a and b are non-Boolean arrays, consider (a - b).any() or (a - b).all() instead.
Rationale
The NumPy developers felt there was no one commonly understood way to evaluate an array in Boolean context: it could mean True if any element is True, or it could mean True if all elements are True, or True if the array has non-zero length, just to name three possibilities.
Since different users might have different needs and different assumptions, the
NumPy developers refused to guess and instead decided to raise a ValueError whenever one tries to evaluate an array in Boolean context. Applying and to two numpy arrays causes the two arrays to be evaluated in Boolean context (by calling __bool__ in Python3 or __nonzero__ in Python2).
I had the same problem (i.e. indexing with multi-conditions, here it's finding data in a certain date range). The (a-b).any() or (a-b).all() seem not working, at least for me.
Alternatively I found another solution which works perfectly for my desired functionality (The truth value of an array with more than one element is ambigous when trying to index an array).
Instead of using suggested code above, use:
numpy.logical_and(a, b)
The reason for the exception is that and implicitly calls bool. First on the left operand and (if the left operand is True) then on the right operand. So x and y is equivalent to bool(x) and bool(y).
However the bool on a numpy.ndarray (if it contains more than one element) will throw the exception you have seen:
>>> import numpy as np
>>> arr = np.array([1, 2, 3])
>>> bool(arr)
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
The bool() call is implicit in and, but also in if, while, or, so any of the following examples will also fail:
>>> arr and arr
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
>>> if arr: pass
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
>>> while arr: pass
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
>>> arr or arr
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
There are more functions and statements in Python that hide bool calls, for example 2 < x < 10 is just another way of writing 2 < x and x < 10. And the and will call bool: bool(2 < x) and bool(x < 10).
The element-wise equivalent for and would be the np.logical_and function, similarly you could use np.logical_or as equivalent for or.
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)
>>> np.logical_and(arr > 1, arr < 3)
array([False, True, False], dtype=bool)
>>> np.bitwise_and(arr > 1, arr < 3)
array([False, True, False], dtype=bool)
>>> (arr > 1) & (arr < 3)
array([False, True, False], dtype=bool)
and bitwise_or (| operator):
>>> np.logical_or(arr <= 1, arr >= 3)
array([ True, False, True], dtype=bool)
>>> np.bitwise_or(arr <= 1, arr >= 3)
array([ True, False, True], dtype=bool)
>>> (arr <= 1) | (arr >= 3)
array([ True, False, True], dtype=bool)
A complete list of logical and binary functions can be found in the NumPy documentation:
"Logic functions"
"Binary operations"
if you work with pandas what solved the issue for me was that i was trying to do calculations when I had NA values, the solution was to run:
df = df.dropna()
And after that the calculation that failed.
Taking up #ZF007's answer, this is not answering your question as a whole, but can be the solution for the same error. I post it here since I have not found a direct solution as an answer to this error message elsewhere on Stack Overflow.
The error, among others, appears when you check whether an array was empty or not.
if np.array([1,2]): print(1) --> ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all().
if np.array([1,2])[0]: print(1) --> no ValueError, but: if np.array([])[0]: print(1) --> IndexError: index 0 is out of bounds for axis 0 with size 0.
if np.array([1]): print(1) --> no ValueError, but again will not help at an array with many elements.
if np.array([]): print(1) --> DeprecationWarning: The truth value of an empty array is ambiguous. Returning False, but in future this will result in an error. Use 'array.size > 0' to check that an array is not empty.
if np.array([]).size is not None: print(1): Taking up a comment by this user, this does not work either. This is since no np.array can ever be the same object as None - that object is unique - and thus will always match is not None (i.e. never match is None) whether or not it's empty.
Doing so:
if np.array([]).size: print(1) solved the error.
This typed error-message also shows while an if-statement comparison is done where there is an array and for example a bool or int. See for example:
... code snippet ...
if dataset == bool:
....
... code snippet ...
This clause has dataset as array and bool is euhm the "open door"... True or False.
In case the function is wrapped within a try-statement you will receive with except Exception as error: the message without its error-type:
The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
Normally, when you compare two single digits the Python regular codes work correctly, but inside an array there are some digits (more than one number) that should be processed in parallel.
For example, let us assume the following:
a = np.array([1, 2, 3])
b = np.array([2, 3, 4])
And you want to check if b >= a: ?
Because, a and b are not single digits and you actually mean if every element of b is greater than the similar number in a, then you should use the following command:
if (b >= a).all():
print("b is greater than a!")
Cause
This error occurs any time that the code attempts to convert a Numpy array to boolean (i.e., to check its truth value, as described in the error message). For a given array a, this can occur:
Explicitly, by using bool(a).
Implicitly with boolean logical operators: a and a, a or a, not a.
Implicitly using the built-in any and all functions. (These can accept a single array, regardless of how many dimensions it has; but cannot accept a list, tuple, set etc. of arrays.)
Implicitly in an if statement, using if a:. While it's normally possible to use any Python object in an if statement, Numpy arrays deliberately break this feature, because it could easily be used to write incorrect code by mistake otherwise.
Numpy arrays and comparisons (==, !=, <, >, <=, >=)
Comparisons have a special meaning for Numpy arrays. We will consider the == operator here; the rest behave analogously. Suppose we have
import numpy as np
>>> a = np.arange(9)
>>> b = a % 3
>>> a
array([0, 1, 2, 3, 4, 5, 6, 7, 8])
>>> b
array([0, 1, 2, 0, 1, 2, 0, 1, 2])
Then, a == b does not mean "give a True or False answer: is a equal to b?", like it would usually mean. Instead, it will compare the values element by element, and evaluate to an array of boolean results for those comparisons:
>>> a == b
array([ True, True, True, False, False, False, False, False, False])
In other words, it does the same kind of broadcasting that mathematical operators (like b = a % 3) do.
It does not make sense to use this result for an if statement, because it is not clear what to do: should we enter the if block, because some of the values matched? Or should we enter the else block, because some of the values didn't match? Here, Numpy applies an important principle from the Zen of Python: "In the face of ambiguity, refuse the temptation to guess."
Thus, Numpy will only allow the array to be converted to bool, if it contains exactly one element. (In some older versions, it will also convert to False for an empty array; but there are good logical reasons why this should also be treated as ambiguous.)
Similarly, comparing a == 4 will not check whether the array is equal to the integer (of course, no array can ever be equal to any integer). Instead, it will broadcast the comparison across the array, giving a similar array of results:
>>> a == 4
array([False, False, False, False, True, False, False, False, False])
Fixing expressions
If the code is explicitly converting to bool, choose between applying .any or .all to the result, as appropriate. As the names suggest, .any will collapse the array to a single boolean, indicating whether any value was truthy; .all will check whether all values were truthy.
>>> (a == 4).all() # `a == 4` contains some `False` values
False
>>> (a == 4).any() # and also some `True` values
True
>>> a.all() # We can check `a` directly as well: `0` is not truthy,
False
>>> a.any() # but other values in `a` are.
True
If the goal is to convert a to boolean element-wise, use a.astype(bool), or (only for numeric inputs) a != 0.
If the code is using boolean logic (and/or/not), use bitwise operators (&/|/~, respectively) instead:
>>> ((a % 2) != 0) & ((a % 3) != 0) # N.B. `&`, not `and`
array([False, True, False, False, False, True, False, True, False])
Note that bitwise operators also offer access to ^ for an exclusive-or of the boolean inputs; this is not supported by logical operators (there is no xor).
For a list (or other sequence) of arrays that need to be combined in the same way (i.e., what the built-ins all and any do), instead build the corresponding (N+1)-dimensional array, and use np.all or np.any along axis 0:
>>> a = np.arange(100) # a larger array for a more complex calculation
>>> sieves = [a % p for p in (2, 3, 5, 7)]
>>> all(sieves) # won't work
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: The truth value of an array with more than one element is ambiguous.
Use a.any() or a.all()
>>> np.all(np.array(sieves), axis=0) # instead:
array([False, True, False, False, False, False, False, False, False,
False, False, True, False, True, False, False, False, True,
False, True, False, False, False, True, False, False, False,
False, False, True, False, True, False, False, False, False,
False, True, False, False, False, True, False, True, False,
False, False, True, False, False, False, False, False, True,
False, False, False, False, False, True, False, True, False,
False, False, False, False, True, False, False, False, True,
False, True, False, False, False, False, False, True, False,
False, False, True, False, False, False, False, False, True,
False, False, False, False, False, False, False, True, False,
False])
Fixing if statements
First, keep in mind that if the code has an if statement that uses a broken expression (like if (a % 3 == 0) or (a % 5 == 0):), then both things will need to be fixed.
Generally, an explicit conversion to bool (using .all() or .any() as above) will avoid an exception:
>>> a = np.arange(20) # enough to illustrate this
>>> if ((a % 3 == 0) | (a % 5 == 0)).any():
... print('there are fizzbuzz values')
...
there are fizzbuzz values
but it might not do what is wanted:
>>> a = np.arange(20) # enough to illustrate this
>>> if ((a % 3 == 0) | (a % 5 == 0)).any():
... a = -1
...
>>> a
-1
If the goal is to operate on each value where the condition is true, then the natural way to do that is to use the mask as a mask. For example, to assign a new value everywhere the condition is true, simply index into the original array with the computed mask, and assign:
>>> a = np.arange(20)
>>> a[(a % 3 == 0) | (a % 5 == 0)] = -1
>>> a
array([-1, 1, 2, -1, 4, -1, -1, 7, 8, -1, -1, 11, -1, 13, 14, -1, 16,
17, -1, 19])
This indexing technique is also useful for finding values that meet a condition. Building on the previous sieves example:
>>> a = np.arange(100)
>>> sieves = [a % p for p in (2, 3, 5, 7)]
>>> a[np.all(np.array(sieves), axis=0)]
array([ 1, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71,
73, 79, 83, 89, 97])
(Exercise: study the code and understand why this result isn't quite a list of primes under 100; then fix it.)
Using Pandas
The Pandas library has Numpy as a dependency, and implements its DataFrame type on top of Numpy's array type. All the same reasoning applies, such that Pandas Series (and DataFrame) objects cannot be used as boolean: see Truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
The Pandas interface for working around the problem is a bit more complicated - and best understood by reading that Q&A. The question specifically covers Series, but the logic generally applies to DataFrames as well. If you need more specific guidance, though, see If condition with a dataframe.
For me, this error occurred on testing, code with error below:
pixels = []
self.pixels = numpy.arange(1, 10)
self.assertEqual(self.pixels, pixels)
This code returned:
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
Because i cannot assert with a list the object returned by method arrange of numpy.
Solution as transform the arrange object of numpy to list, my choice was using the method toList(), as following:
pixels = []
self.pixels = numpy.arange(1, 10).toList()
self.assertEqual(self.pixels, pixels)
Simplest answer is use "&" instead of "and".
>>> import numpy as np
>>> arr = np.array([1, 4, 2, 7, 5])
>>> arr[(arr > 3) and (arr < 6)] # this will fail
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
>>> arr[(arr > 3) & (arr < 6)] # this will succeed
array([4, 5])

The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()? [duplicate]

Let x be a NumPy array. The following:
(x > 1) and (x < 3)
Gives the error message:
ValueError: The truth value of an array with more than one element is
ambiguous. Use a.any() or a.all()
How do I fix this?
If a and b are Boolean NumPy arrays, the & operation returns the elementwise-and of them:
a & b
That returns a Boolean array. To reduce this to a single Boolean value, use either
(a & b).any()
or
(a & b).all()
Note: if a and b are non-Boolean arrays, consider (a - b).any() or (a - b).all() instead.
Rationale
The NumPy developers felt there was no one commonly understood way to evaluate an array in Boolean context: it could mean True if any element is True, or it could mean True if all elements are True, or True if the array has non-zero length, just to name three possibilities.
Since different users might have different needs and different assumptions, the
NumPy developers refused to guess and instead decided to raise a ValueError whenever one tries to evaluate an array in Boolean context. Applying and to two numpy arrays causes the two arrays to be evaluated in Boolean context (by calling __bool__ in Python3 or __nonzero__ in Python2).
I had the same problem (i.e. indexing with multi-conditions, here it's finding data in a certain date range). The (a-b).any() or (a-b).all() seem not working, at least for me.
Alternatively I found another solution which works perfectly for my desired functionality (The truth value of an array with more than one element is ambigous when trying to index an array).
Instead of using suggested code above, use:
numpy.logical_and(a, b)
The reason for the exception is that and implicitly calls bool. First on the left operand and (if the left operand is True) then on the right operand. So x and y is equivalent to bool(x) and bool(y).
However the bool on a numpy.ndarray (if it contains more than one element) will throw the exception you have seen:
>>> import numpy as np
>>> arr = np.array([1, 2, 3])
>>> bool(arr)
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
The bool() call is implicit in and, but also in if, while, or, so any of the following examples will also fail:
>>> arr and arr
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
>>> if arr: pass
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
>>> while arr: pass
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
>>> arr or arr
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
There are more functions and statements in Python that hide bool calls, for example 2 < x < 10 is just another way of writing 2 < x and x < 10. And the and will call bool: bool(2 < x) and bool(x < 10).
The element-wise equivalent for and would be the np.logical_and function, similarly you could use np.logical_or as equivalent for or.
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)
>>> np.logical_and(arr > 1, arr < 3)
array([False, True, False], dtype=bool)
>>> np.bitwise_and(arr > 1, arr < 3)
array([False, True, False], dtype=bool)
>>> (arr > 1) & (arr < 3)
array([False, True, False], dtype=bool)
and bitwise_or (| operator):
>>> np.logical_or(arr <= 1, arr >= 3)
array([ True, False, True], dtype=bool)
>>> np.bitwise_or(arr <= 1, arr >= 3)
array([ True, False, True], dtype=bool)
>>> (arr <= 1) | (arr >= 3)
array([ True, False, True], dtype=bool)
A complete list of logical and binary functions can be found in the NumPy documentation:
"Logic functions"
"Binary operations"
if you work with pandas what solved the issue for me was that i was trying to do calculations when I had NA values, the solution was to run:
df = df.dropna()
And after that the calculation that failed.
Taking up #ZF007's answer, this is not answering your question as a whole, but can be the solution for the same error. I post it here since I have not found a direct solution as an answer to this error message elsewhere on Stack Overflow.
The error, among others, appears when you check whether an array was empty or not.
if np.array([1,2]): print(1) --> ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all().
if np.array([1,2])[0]: print(1) --> no ValueError, but: if np.array([])[0]: print(1) --> IndexError: index 0 is out of bounds for axis 0 with size 0.
if np.array([1]): print(1) --> no ValueError, but again will not help at an array with many elements.
if np.array([]): print(1) --> DeprecationWarning: The truth value of an empty array is ambiguous. Returning False, but in future this will result in an error. Use 'array.size > 0' to check that an array is not empty.
if np.array([]).size is not None: print(1): Taking up a comment by this user, this does not work either. This is since no np.array can ever be the same object as None - that object is unique - and thus will always match is not None (i.e. never match is None) whether or not it's empty.
Doing so:
if np.array([]).size: print(1) solved the error.
This typed error-message also shows while an if-statement comparison is done where there is an array and for example a bool or int. See for example:
... code snippet ...
if dataset == bool:
....
... code snippet ...
This clause has dataset as array and bool is euhm the "open door"... True or False.
In case the function is wrapped within a try-statement you will receive with except Exception as error: the message without its error-type:
The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
Normally, when you compare two single digits the Python regular codes work correctly, but inside an array there are some digits (more than one number) that should be processed in parallel.
For example, let us assume the following:
a = np.array([1, 2, 3])
b = np.array([2, 3, 4])
And you want to check if b >= a: ?
Because, a and b are not single digits and you actually mean if every element of b is greater than the similar number in a, then you should use the following command:
if (b >= a).all():
print("b is greater than a!")
Cause
This error occurs any time that the code attempts to convert a Numpy array to boolean (i.e., to check its truth value, as described in the error message). For a given array a, this can occur:
Explicitly, by using bool(a).
Implicitly with boolean logical operators: a and a, a or a, not a.
Implicitly using the built-in any and all functions. (These can accept a single array, regardless of how many dimensions it has; but cannot accept a list, tuple, set etc. of arrays.)
Implicitly in an if statement, using if a:. While it's normally possible to use any Python object in an if statement, Numpy arrays deliberately break this feature, because it could easily be used to write incorrect code by mistake otherwise.
Numpy arrays and comparisons (==, !=, <, >, <=, >=)
Comparisons have a special meaning for Numpy arrays. We will consider the == operator here; the rest behave analogously. Suppose we have
import numpy as np
>>> a = np.arange(9)
>>> b = a % 3
>>> a
array([0, 1, 2, 3, 4, 5, 6, 7, 8])
>>> b
array([0, 1, 2, 0, 1, 2, 0, 1, 2])
Then, a == b does not mean "give a True or False answer: is a equal to b?", like it would usually mean. Instead, it will compare the values element by element, and evaluate to an array of boolean results for those comparisons:
>>> a == b
array([ True, True, True, False, False, False, False, False, False])
In other words, it does the same kind of broadcasting that mathematical operators (like b = a % 3) do.
It does not make sense to use this result for an if statement, because it is not clear what to do: should we enter the if block, because some of the values matched? Or should we enter the else block, because some of the values didn't match? Here, Numpy applies an important principle from the Zen of Python: "In the face of ambiguity, refuse the temptation to guess."
Thus, Numpy will only allow the array to be converted to bool, if it contains exactly one element. (In some older versions, it will also convert to False for an empty array; but there are good logical reasons why this should also be treated as ambiguous.)
Similarly, comparing a == 4 will not check whether the array is equal to the integer (of course, no array can ever be equal to any integer). Instead, it will broadcast the comparison across the array, giving a similar array of results:
>>> a == 4
array([False, False, False, False, True, False, False, False, False])
Fixing expressions
If the code is explicitly converting to bool, choose between applying .any or .all to the result, as appropriate. As the names suggest, .any will collapse the array to a single boolean, indicating whether any value was truthy; .all will check whether all values were truthy.
>>> (a == 4).all() # `a == 4` contains some `False` values
False
>>> (a == 4).any() # and also some `True` values
True
>>> a.all() # We can check `a` directly as well: `0` is not truthy,
False
>>> a.any() # but other values in `a` are.
True
If the goal is to convert a to boolean element-wise, use a.astype(bool), or (only for numeric inputs) a != 0.
If the code is using boolean logic (and/or/not), use bitwise operators (&/|/~, respectively) instead:
>>> ((a % 2) != 0) & ((a % 3) != 0) # N.B. `&`, not `and`
array([False, True, False, False, False, True, False, True, False])
Note that bitwise operators also offer access to ^ for an exclusive-or of the boolean inputs; this is not supported by logical operators (there is no xor).
For a list (or other sequence) of arrays that need to be combined in the same way (i.e., what the built-ins all and any do), instead build the corresponding (N+1)-dimensional array, and use np.all or np.any along axis 0:
>>> a = np.arange(100) # a larger array for a more complex calculation
>>> sieves = [a % p for p in (2, 3, 5, 7)]
>>> all(sieves) # won't work
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: The truth value of an array with more than one element is ambiguous.
Use a.any() or a.all()
>>> np.all(np.array(sieves), axis=0) # instead:
array([False, True, False, False, False, False, False, False, False,
False, False, True, False, True, False, False, False, True,
False, True, False, False, False, True, False, False, False,
False, False, True, False, True, False, False, False, False,
False, True, False, False, False, True, False, True, False,
False, False, True, False, False, False, False, False, True,
False, False, False, False, False, True, False, True, False,
False, False, False, False, True, False, False, False, True,
False, True, False, False, False, False, False, True, False,
False, False, True, False, False, False, False, False, True,
False, False, False, False, False, False, False, True, False,
False])
Fixing if statements
First, keep in mind that if the code has an if statement that uses a broken expression (like if (a % 3 == 0) or (a % 5 == 0):), then both things will need to be fixed.
Generally, an explicit conversion to bool (using .all() or .any() as above) will avoid an exception:
>>> a = np.arange(20) # enough to illustrate this
>>> if ((a % 3 == 0) | (a % 5 == 0)).any():
... print('there are fizzbuzz values')
...
there are fizzbuzz values
but it might not do what is wanted:
>>> a = np.arange(20) # enough to illustrate this
>>> if ((a % 3 == 0) | (a % 5 == 0)).any():
... a = -1
...
>>> a
-1
If the goal is to operate on each value where the condition is true, then the natural way to do that is to use the mask as a mask. For example, to assign a new value everywhere the condition is true, simply index into the original array with the computed mask, and assign:
>>> a = np.arange(20)
>>> a[(a % 3 == 0) | (a % 5 == 0)] = -1
>>> a
array([-1, 1, 2, -1, 4, -1, -1, 7, 8, -1, -1, 11, -1, 13, 14, -1, 16,
17, -1, 19])
This indexing technique is also useful for finding values that meet a condition. Building on the previous sieves example:
>>> a = np.arange(100)
>>> sieves = [a % p for p in (2, 3, 5, 7)]
>>> a[np.all(np.array(sieves), axis=0)]
array([ 1, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71,
73, 79, 83, 89, 97])
(Exercise: study the code and understand why this result isn't quite a list of primes under 100; then fix it.)
Using Pandas
The Pandas library has Numpy as a dependency, and implements its DataFrame type on top of Numpy's array type. All the same reasoning applies, such that Pandas Series (and DataFrame) objects cannot be used as boolean: see Truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
The Pandas interface for working around the problem is a bit more complicated - and best understood by reading that Q&A. The question specifically covers Series, but the logic generally applies to DataFrames as well. If you need more specific guidance, though, see If condition with a dataframe.
For me, this error occurred on testing, code with error below:
pixels = []
self.pixels = numpy.arange(1, 10)
self.assertEqual(self.pixels, pixels)
This code returned:
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
Because i cannot assert with a list the object returned by method arrange of numpy.
Solution as transform the arrange object of numpy to list, my choice was using the method toList(), as following:
pixels = []
self.pixels = numpy.arange(1, 10).toList()
self.assertEqual(self.pixels, pixels)
Simplest answer is use "&" instead of "and".
>>> import numpy as np
>>> arr = np.array([1, 4, 2, 7, 5])
>>> arr[(arr > 3) and (arr < 6)] # this will fail
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
>>> arr[(arr > 3) & (arr < 6)] # this will succeed
array([4, 5])

python numpy strange boolean arithmetic behaviour

Why is it, in python/numpy:
from numpy import asarray
bools=asarray([False,True])
print(bools)
[False True]
print(1*bools, 0+bools, 0-bools) # False, True are valued as 0, 1
[0 1] [0 1] [ 0 -1]
print(-2*bools, -bools*2) # !? expected same result! :-/
[0 -2] [2 0]
print(-bools) # this is the reason!
[True False]
I consider it weird that -bools returns logical_not(bools), because in all other cases the behaviour is "arithmetic", not "logical".
One who wants to use an array of booleans as a 0/1 mask (or "characteristic function") is forced to use somehow involute expressions such as (0-bools) or (-1)*bools, and can easily incur into bugs if he forgets about this.
Why is it so, and what would be the best acceptable way to obtain the desired behaviour? (beside commenting of course)
Its all about operator order and data types.
>>> import numpy as np
>>> B = np.array([0, 1], dtype=np.bool)
>>> B
array([False, True], dtype=bool)
With numpy, boolean arrays are treated as that, boolean arrays. Every operation applied to them, will first try to maintain the data type. That is way:
>>> -B
array([ True, False], dtype=bool)
and
>>> ~B
array([ True, False], dtype=bool)
which are equivalent, return the element-wise negation of its elements. Note however that using -B throws a warning, as the function is deprecated.
When you use things like:
>>> B + 1
array([1, 2])
B and 1 are first casted under the hood to the same data type. In data-type promotions, the boolean array is always casted to a numeric array. In the above case, B is casted to int, which is similar as:
>>> B.astype(int) + 1
array([1, 2])
In your example:
>>> -B * 2
array([2, 0])
First the array B is negated by the operator - and then multiplied by 2. The desired behaviour can be adopted either by explicit data conversion, or adding brackets to ensure proper operation order:
>>> -(B * 2)
array([ 0, -2])
or
>>> -B.astype(int) * 2
array([ 0, -2])
Note that B.astype(int) can be replaced without data-copy by B.view(np.int8), as boolean are represented by characters and have thus 8 bits, the data can be viewed as integer with the .view method without needing to convert it.
>>> B.view(np.int8)
array([0, 1], dtype=int8)
So, in short, B.view(np.int8) or B.astype(yourtype) will always ensurs that B is a [0,1] numeric array.
Numpy arrays are homogenous—all elements have the same type for a given array, and the array object stores what type that is. When you create an array with True and False, it is an array of type bool and operators behave on the array as such. It's not surprising, then, that you get logical negation happening in situations that would be logical negation for a normal bool. When you use the arrays for integer math, then they are converted to 1's and 0's. Of all your examples, those are the more anomalous cases, that is, it's behavior that shouldn't be relied upon in good code.
As suggested in the comments, if you want to do math with an array of 0's and 1's, it's better to just make an array of 0's and 1's. However, depending on what you want to do with them, you might be better served looking into functions like numpy.where().

Numpy array update command explanation

How is this operation called technically and what other functionalities does it allow for:
Z[1:-1,1:-1][birth|survive]=1. Where Z is a 4x4 array and birth and survive are same size Boolean arrays. I understand what this code does, but would like to know how is this operation called and what else can I do with it (talking about this latter part [birth|survive]).
The pipe | is the bitwise or operator. Therefore, birth|survive is the equivalent to np.bitwise_or(birth, survive). Presumably birth and survive are boolean arrays, so the output is a boolean array with the straightforward or behavior:
a = np.array([True, True, False, False])
b = np.array([True, False, False, True])
a|b
# array([ True, True, False, True], dtype=bool)
For integers, each bit is considered and an integer array is returned where for each digit in the binary representation has been or'ed. There is a better explanation on its behavior and some examples at the documentation page.
Once you've created the boolean array from birth|survive, you are using it to do a boolean index into the Z array. Most simply, this can be shown with:
a = np.array([1,2,3])
b = np.array([True, False, True])
a[b] # the elements of a where b is True
# array([1, 3])
Since it's on the left side of the assignment =, python will assign the value 1 to every point in Z where birth or survive is True:
a[b] = 99
a
# array([99, 2, 99])

Categories