Skip to content
Advertisement

Numpy diff inverted operation?

Working with numpy.diff function, suppose this simple case:

>>> x = np.array([1, 2, 4, 7, 0])
>>> x_diff = np.diff(x)
array([ 1,  2,  3, -7])

How can I get easily x back to original scale not differenced? I suppose there is something with numpy.cumsum().

Advertisement

Answer

Concatenate with the first element and then use cumsum

np.r_[x[0], x_diff].cumsum()

For concatenating, we can also use np.hstack, like so –

np.hstack((x[0], x_diff)).cumsum()

Or with np.concatenate for the concatenation –

np.concatenate(([x[0]], x_diff)).cumsum()
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement