Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use a.any() or a.all()

Tags:

python

numpy

x = np.arange(0,2,0.5) valeur = 2*x  if valeur <= 0.6:     print ("this works") else:        print ("valeur is too high") 

here is the error I get:

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

I have read several posts about a.any() or a.all() but still can't find a way that really clearly explain how to fix the problem. I see why Python does not like what I wrote but I am not sure how to fix it.

like image 771
Moe Steen Avatar asked Dec 26 '15 15:12

Moe Steen


People also ask

How do you use a ANY () or a all ()?

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.

What is the use of all and any function in Numpy?

The numpy. any() function returns True if at least one item in a Numpy array evaluates to True. The numpy. all() function returns True only if all items in a Numpy array evaluate as True.

What does all () Numpy?

all() in Python. The numpy. all() function tests whether all array elements along the mentioned axis evaluate to True.

How do you check if all values in an array are true Python?

Python all() Function The all() function returns True if all items in an iterable are true, otherwise it returns False. If the iterable object is empty, the all() function also returns True.


2 Answers

There is one more way you can get this

import numpy as np  a = np.array([1,2,3,4]) b = np.array([5,6,7,8]) c = np.array([1,2,3,4])  print((a == b ).all())  #False print((a == c ).all())   # True print((a == b ).any())   #False print((a == c ).any())   #True print((a > 3 ).all())    #False 
like image 38
Prajot Kuvalekar Avatar answered Oct 09 '22 03:10

Prajot Kuvalekar


If you take a look at the result of valeur <= 0.6, you can see what’s causing this ambiguity:

>>> valeur <= 0.6 array([ True, False, False, False], dtype=bool) 

So the result is another array that has in this case 4 boolean values. Now what should the result be? Should the condition be true when one value is true? Should the condition be true only when all values are true?

That’s exactly what numpy.any and numpy.all do. The former requires at least one true value, the latter requires that all values are true:

>>> np.any(valeur <= 0.6) True >>> np.all(valeur <= 0.6) False 
like image 60
poke Avatar answered Oct 09 '22 04:10

poke