Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to take n-th order discrete sum of numpy array (sum equivalent of numpy.diff)

I know that it is possible to take the n-th order discrete difference of a numpy array by using the numpy function numpy.diff(), but is there a way to do the same with the n-th order discrete sum?

Let's say we have a numpy array, A = np.arange(10). The expected result for the 1st order discrete sum would be:

array([  1.,   3.,   5.,   7.,   9.,  11.,  13.,  15.,  17.]) 

which I can get from doing:

N = A.shape[0]
B = np.zeros(N-1)

for i in range(N-1):
    B[i] = A[i+1] + A[i]

But is there a function available to avoid having to use a for loop?

like image 968
pbreach Avatar asked May 06 '15 23:05

pbreach


People also ask

What is diff () in NumPy give example?

diff() function calculates the difference between subsequent values in a NumPy array. For example, np. diff([1, 2, 4]) returns the difference array [1 2] .

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.

How do you find the sum of all elements in a NumPy array?

sum() in Python. numpy. sum(arr, axis, dtype, out) : This function returns the sum of array elements over the specified axis.

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.


1 Answers

A[i+1] for for i in range(N-1) would be covered by A[1:] and similarly A[i] for the same iteration means A[:-1]. So, basically you can sum these two versions of the input array to have a vectorized output in B, like so -

B = A[:-1] + A[1:]
like image 72
Divakar Avatar answered Oct 21 '22 07:10

Divakar