2

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?

1
  • 1
    Unless you've aliased it, it's a Python built-in... Commented Jun 7, 2017 at 21:43

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Nice explanation and timing example. Are you sure about the side note though? 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"
The comparison and arithmetic operators like > 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. :)
Ah see the distinction now :)
2

A numpy array is iterable, which is all the built-in any expects of its argument. any returns False if all of the elements of the iterable are falsey, which all the zeros are. Then the comparison False > 0 is also False, giving you the observed value.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.