Skip to content
Advertisement

What is the inverse of the numpy cumsum function?

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

Advertisement

Answer

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

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement