What is the inverse of the numpy cumsum function? What is the inverse of the numpy cumsum function? python python

What is the inverse of the numpy cumsum function?


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


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)


If you want to keep z, you can use np.ediff1d:

x = np.ediff1d(z, to_begin=z[0])