NumPy ndarray.all() vs np.all(ndarray) vs all(ndarray)
The difference between np.all(a)
and a.all()
is simple:
- If
a
is anumpy.array
thennp.all()
will simply calla.all()
. - If
a
is not anumpy.array
thenp.all()
call will convert it to annumpy.array
and then calla.all()
.a.all()
on the other hand will fail becausea
wasn't anumpy.array
and therefore probably has noall
method.
The difference between np.all
and all
is more complicated.
- The
all
function works on any iterable (includinglist
,set
s,generators
, ...).np.all
works only fornumpy.array
s (including everything that can be converted to a numpy array, i.e.list
s andtuple
s). np.all
processes anarray
with specified data type, that makes it pretty efficient when comparing for!= 0
.all
however needs to evaluatebool
for each item, that's much slower.- processing arrays with python functions is pretty slow because each item in the array needs to be converted to a python object.
np.all
doesn't need to do that conversion.
Note that the timings depend also on the type of your a
. If you process a python list all
can be faster for relativly short lists. If you process an array, np.all
and a.all()
will be faster in almost all cases (except maybe for object
arrays, but I won't go down that path, that way lies madness).
I'll take a swing at this
np.all
is a generic function which will work with different data types, under the hood this probably looks forndarray.all
which is why it's slightly slower.all
is a python bulit-in function see https://docs.python.org/2/library/functions.html#all.ndarray.all
is method of the 'numpy.ndarray' object, calling this directly may be faster.
I suspect that numpy's functions do more to evaluate an array element as a boolean, likely in some generic numeric-first way, while the builtin all()
does nothing, since the elements are already booleans.
I wonder how different the results would be with integers of floats.