Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

`numpy.sum` vs. `ndarray.sum`

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.?

like image 436
p-value Avatar asked Feb 23 '18 06:02

p-value


People also ask

What is the difference between NP sum and sum?

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.

Is NumPy array and Ndarray same?

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.

How do I sum NumPy Ndarray?

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.

How do I sum two NumPy arrays?

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.


1 Answers

I'd imagine it is becasue np.sum() and the like needs to explicitly convert the inputs to ndarray first (using np.asanyarray) checks a few other .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.

like image 133
Daniel F Avatar answered Oct 01 '22 14:10

Daniel F