13

I have a numpy array like

x=np.array([1,2,3,4])

I want to create another numpy array y which is the cumulative sum of x, so that

y=np.array([1,3,6,10])

What is a good num-Pythonic way to do this?

2 Answers 2

27
y = np.cumsum(x)

See http://docs.scipy.org/doc/numpy/reference/generated/numpy.cumsum.html

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

1 Comment

@Dan , Can I get the result in-place. I want the result is also in x, not another array y
8

Another option is:

y = np.add.accumulate(x)

which is often times faster than np.cumsum even though the documentation says they are equivalent.

1 Comment

I would like to say that I also tested this and accumulate is slightly faster on my system too: %timeit np.add.accumulate(range(20000000)) ---> 3.06 s ± 40.1 and for cumsum I get 3.08 s ± 24.7 ms

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.