Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Numpy.cumsum in reverse

Tags:

python

numpy

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?

like image 451
Amxx Avatar asked Feb 19 '15 21:02

Amxx


People also ask

What does NumPy Cumsum return?

cumsum. Return the cumulative sum of the elements along a given axis.

What is reverse cumulative sum?

Description. Returns a vector of cumulative sums of the input values, running in reverse order. That is, the i th entry in the output is the sum of entries i to n in the input, where n is the length of the input.

What does Cumsum mean in Python?

cumsum() function is used when we want to compute the cumulative sum of array elements over a given axis. Syntax : numpy.cumsum(arr, axis=None, dtype=None, out=None) Parameters : arr : [array_like] Array containing numbers whose cumulative sum is desired.


2 Answers

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]]])
like image 67
SmCaterpillar Avatar answered Oct 05 '22 07:10

SmCaterpillar


How about

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

See this question which discusses reversing numpy arrays.

like image 25
dg99 Avatar answered Oct 05 '22 08:10

dg99