Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the inverse of the numpy cumsum function?

Tags:

If I have z = cumsum( [ 0, 1, 2, 6, 9 ] ), which gives me z = [ 0, 1, 3, 9, 18 ], how can I get back to the original array [ 0, 1, 2, 6, 9 ] ?

like image 544
scottlittle Avatar asked Jul 29 '16 20:07

scottlittle


People also ask

What does Numpy Cumsum return?

cumsum. Return the cumulative sum of the elements along a given axis.

What is Cumsum Numpy?

cumsum() function is used when we want to compute the cumulative sum of array elements over a given axis. Syntax : numpy.cumsum(arr, axis=None, dtype=None, out=None) Parameters : arr : [array_like] Array containing numbers whose cumulative sum is desired.


2 Answers

z[1:] -= z[:-1].copy() 

Short and sweet, with no slow Python loops. We take views of all but the first element (z[1:]) and all but the last (z[:-1]), and subtract elementwise. The copy makes sure we subtract the original element values instead of the values we're computing. (On NumPy 1.13 and up, you can skip the copy call.)

like image 136
user2357112 supports Monica Avatar answered Dec 22 '22 16:12

user2357112 supports Monica


You can use np.diff to compute elements 1...N which will take the difference between any two elements. This is the opposite of cumsum. The only difference is that diff will not return the first element, but the first element is the same in the original and cumsum output so we just re-use that value.

orig = np.insert(np.diff(z), 0, z[0]) 

Rather than insert, you could also use np.concatenate

orig = np.concatenate((np.array(z[0]).reshape(1,), np.diff(z))) 

We could also just copy and replace elements 1...N

orig = z.copy() orig[1:] = np.diff(z) 
like image 36
Suever Avatar answered Dec 22 '22 16:12

Suever