2

Forgive me if this has been asked before, I couldn't find it. I am trying to progressively sum a numpy array into a new numpy array using vector operations. What I mean by this is that the 2nd index of the new array is equal to the 1st + 2nd index of the old array. or A[n] = B[0] + B[1] ... + B[n]. I know how to do this using a for loop but I'm looking for a vectorized solution.

Here is my non-vectorized solution:

import numpy as np  
A = np.arange(10)
B = np.empty(10)

for i in range(len(A)):
    B[i] = sum(A[0:i+1])

print(B)
1

2 Answers 2

5

You can do it like this:

import numpy as np  

A = np.arange(10)
B = np.cumsum(A)
# [ 0  1  3  6 10 15 21 28 36 45]

Thanks

Sign up to request clarification or add additional context in comments.

Comments

1

The "progressive" sum is called cumulative sum. Use NumPy's cumsum for this.

Using your example and comparing B to np.cumsum(A) results in equal arrays:

>>> import numpy as np
>>> A = np.arange(10)
>>> B = np.empty(10)
>>> for i in range(len(A)):
...     B[i] = sum(A[0:i+1])
... 
>>> np.array_equal(B, np.cumsum(A))
True

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.