Perform a reverse cumulative sum on a numpy array

atomh33ls picture atomh33ls · May 14, 2013 · Viewed 23.4k times · Source

Can anyone recommend a way to do a reverse cumulative sum on a numpy array?

Where 'reverse cumulative sum' is defined as below (I welcome any corrections on the name for this procedure):

if

x = np.array([0,1,2,3,4])

then

np.cumsum(x)

gives

array([0,1,3,6,10])

However, I would like to get

array([10,10,9,7,4]

Can anyone suggest a way to do this?

Answer

atomh33ls picture atomh33ls · May 14, 2013

This does it:

np.cumsum(x[::-1])[::-1]