Why is it possible to use any directly as a function on a numpy array?
In [30]: any(np.zeros(4))>0
Out[30]: False
I thought numpy's any()-method was on the array itself?
Is this the python function or the actual numpy method?
Why is it possible to use any directly as a function on a numpy array?
In [30]: any(np.zeros(4))>0
Out[30]: False
I thought numpy's any()-method was on the array itself?
Is this the python function or the actual numpy method?
For one-dimensional arrays it works because the built-in Python-any-function just requires an iterable with items that can be cast to bools (and a one-dimensional array satisfies these conditions) but for multidimensional arrays it won't work:
>>> import numpy as np
>>> any(np.ones((10, 10)))
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
>>> np.any(np.ones((10, 10)))
True
That's because if you iterate over a array you iterate over the first dimension, if you have a multidimensional array you'll get an array (not a number) in each iteration. These arrays can't be cast to bools. So it throws the exception.
But np.any will be faster (in most cases) on arrays than any because it's aware of the input-type (array) and it can avoid the python iteration that any needs:
In [0]: arr = np.zeros((1000))
In [1]: %timeit any(arr)
Out[1]: 215 µs ± 4.29 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
In [2]: %timeit np.any(arr)
Out[2]: 31.2 µs ± 1.41 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
As a side note, you probably wanted to use any(np.zeros(4) > 0) instead of any(np.zeros(4))>0.
The first one checks if any element in your array is above zero, while the second checks if the result of any (True if any element is not zero) is above zero.
any(np.zeros(4)).__eq__(0) ==> True, any(np.zeros(4)).__lt__(0) ==> False etc, which looks very much the same as "check if any element is equal to/above/… zero"> do element-wise operations/checks on an array, so I'm pretty sure. Except you wanted to check if the result of any is greater than 0. For example any(np.array([-1, 0, 0])) > 0 returns True but any(np.array([-1, 0, 0]) > 0) returns False. It depends what you need (and you haven't said) so maybe it's me who is wrong. :)