简体   繁体   中英

Why does Pythons “any()” function work on numpy array?

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 bool s (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 array s can't be cast to bool s. 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM