Simplest I can think of and that produces your result is
import numpy as np
x = np.arange(10)
x[::-1].cumsum()[::-1]
which gives
array([45, 45, 44, 42, 39, 35, 30, 24, 17, 9])
EDIT: As dg99 pointed out, there's also a post about the efficiency of reversing an array. Accordingly, [::-1]
seems to be the best you can get. Thus, x[::-1].cumsum()[::-1]
also seems to be the most efficient way to do your reverse cumsum.
2nd EDIT:
For completeness, if you have a multi-dimensional array, you can get the reverse cumsum along the innermost dimension via:
x[...,::-1].cumsum(axis=-1)[...,::-1]
For instance,
x = np.array(((range(10), range(10)), (range(10), range(10))))
print(x)
prints
array([[[0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]],
[[0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]]])
and
x[...,::-1].cumsum(axis=-1)[...,::-1]
returns
array([[[45, 45, 44, 42, 39, 35, 30, 24, 17, 9],
[45, 45, 44, 42, 39, 35, 30, 24, 17, 9]],
[[45, 45, 44, 42, 39, 35, 30, 24, 17, 9],
[45, 45, 44, 42, 39, 35, 30, 24, 17, 9]]])