scottlittle scottlittle - 3 months ago 25
Python Question

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

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.