-1

If I have an array [a,b,c], how can I convert it to [a+b+c, b+c, c] in the most efficient way?

(a, b, c) are floats.

Thanks!

Galen BlueTalon
  • 173
  • 4
  • 20
  • Does this answer your question? [Perform a reverse cumulative sum on a numpy array](https://stackoverflow.com/questions/16541618/perform-a-reverse-cumulative-sum-on-a-numpy-array) – Prasanna Nov 15 '21 at 23:27

2 Answers2

2

You can use np.cumsum:

import numpy as np

a = np.array([1, 2, 3])
print(np.cumsum(a[::-1])[::-1])
# Outputs [6 5 3]
enzo
  • 9,861
  • 3
  • 15
  • 38
1

Use numpy.cumsum() on the reversed array, then reverse it again. cumsum([a,b,c]) returns [a,a+b,a+b+c].

import numpy as np

x = [3,7,14]

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

print(y)
ichthyophile
  • 107
  • 8