5

Here is cumsum in the forward direction:

> import numpy as np
> np.arange(10)
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
> np.cumsum(np.arange(10))
array([ 0,  1,  3,  6, 10, 15, 21, 28, 36, 45])

I would like to perform cumsum in the reverse direction, which would give me

array([45, 45, 44, 42, 39, 35, 30, 24, 17, 9])

What is the simplest and most efficient way to do that?

dg99
  • 5,456
  • 3
  • 37
  • 49
Amxx
  • 3,020
  • 2
  • 24
  • 45

2 Answers2

8

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]]])
Community
  • 1
  • 1
SmCaterpillar
  • 6,683
  • 7
  • 42
  • 70
1

How about

np.cumsum(np.arange(10)[::-1])

See this question which discusses reversing numpy arrays.

Community
  • 1
  • 1
dg99
  • 5,456
  • 3
  • 37
  • 49