Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if variable is defined with Numpy array?

Tags:

python

numpy

Sometimes I have a situation where I want to test whether a variable is 0 or None or not. In pure Python, this is simply

foo == True

but when foo is possibly a Numpy object (such as numpy.ndarray), this does not work anymore and I get the error:

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

and in this case I want a.any(), however this fails on non-iterable objects.

Of course I can explicitly check if foo is 0 or None, but I am wondering if there is a more elegant way to do this.

How can I check if an arbitrary object (both iterable and not) is True or not?

like image 562
Tim Avatar asked Oct 19 '12 12:10

Tim


1 Answers

Just use np.all or np.any instead of the .all method. np.all will create an array if it is not one yet.

like image 186
seberg Avatar answered Sep 22 '22 00:09

seberg