For a 1-D numpy
array a
, I thought that np.sum(a)
and a.sum()
are equivalent functions, but I just did a simple experiment, and it seems that the latter is always a bit faster:
In [1]: import numpy as np
In [2]: a = np.arange(10000)
In [3]: %timeit np.sum(a)
The slowest run took 16.85 times longer than the fastest. This could mean that an intermediate result is being cached.
100000 loops, best of 3: 6.46 µs per loop
In [4]: %timeit a.sum()
The slowest run took 19.80 times longer than the fastest. This could mean that an intermediate result is being cached.
100000 loops, best of 3: 5.25 µs per loop
Why is there a difference?
Does this mean that we should always use the numpy.ndarray
version of functions like sum
, mean
, std
, etc.?
Pythons sum iterates over the iterable (in this case the list or array) and adds all elements. NumPys sum method iterates over the stored C array and adds these C values and finally wraps that value in a Python type (in this case numpy. int32 (or numpy. int64 ) and returns it.
numpy. array is just a convenience function to create an ndarray ; it is not a class itself. You can also create an array using numpy. ndarray , but it is not the recommended way.
sum() function is available in the NumPy package of Python. This function is used to compute the sum of all elements, the sum of each row, and the sum of each column of a given array. Essentially, this sum ups the elements of an array, takes the elements within a ndarray, and adds them together.
To add the two arrays together, we will use the numpy. add(arr1,arr2) method. In order to use this method, you have to make sure that the two arrays have the same length. If the lengths of the two arrays are not the same, then broadcast the size of the shorter array by adding zero's at extra indexes.
I'd imagine it is becasue np.sum()
and the like needs to explicitly convert the inputs to checks a few other ndarray
first (using np.asanyarray
).sum
functions before settling on the ndarray.sum
method in order to allow operation on lists, tuples, etc.
On the other hand, ndarray.sum()
is a method of the ndarray
class and thus doesn't need to do any checking.
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