In numpy, we can check that whether none of the elements of given array is zero or not with the help of numpy. all() function. In this function pass an array as parameter. If any of one element of the passed array is zero then it returns False otherwise it returns True boolean value.
Checking correct variable type. To test that F is an array, we can use isinstance(F, np. ndarray) ( ndarray is the name of the array type in numpy ).
None is an alias for NP. newaxis. It creates an axis with length 1. This can be useful for matrix multiplcation etc.
Using not a
to test whether a
is None
assumes that the other possible values of a
have a truth value of True
. However, most NumPy arrays don't have a truth value at all, and not
cannot be applied to them.
If you want to test whether an object is None
, the most general, reliable way is to literally use an is
check against None
:
if a is None:
...
else:
...
This doesn't depend on objects having a truth value, so it works with NumPy arrays.
Note that the test has to be is
, not ==
. is
is an object identity test. ==
is whatever the arguments say it is, and NumPy arrays say it's a broadcasted elementwise equality comparison, producing a boolean array:
>>> a = numpy.arange(5)
>>> a == None
array([False, False, False, False, False])
>>> if a == None:
... pass
...
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()
On the other side of things, if you want to test whether an object is a NumPy array, you can test its type:
# Careful - the type is np.ndarray, not np.array. np.array is a factory function.
if type(a) is np.ndarray:
...
else:
...
You can also use isinstance
, which will also return True
for subclasses of that type (if that is what you want). Considering how terrible and incompatible np.matrix
is, you may not actually want this:
# Again, ndarray, not array, because array is a factory function.
if isinstance(a, np.ndarray):
...
else:
...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With