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?
cumsum. Return the cumulative sum of the elements along a given axis.
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.
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.
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]]])
How about
np.cumsum(np.arange(10)[::-1])
See this question which discusses reversing numpy arrays.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With