Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Numpy : cumulative difference in a list

I’m stuck on a iteration problem.
I have a list of numbers, like: list = [100, 70, 25, 10, 5].
I would like to iterate over the list and generate a new array, such that each "result" becomes the new number from which the next is subtracted:

100-70 = 30

30 (result) – 25 = 5

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

5 (result) – 10 = -5

-5 (result) – 5 = -10

(I think you get the idea)

new_array = [30, 5, -5, -10]

I am not able to arrive at the solution with Numpy.
Any help is appreciated!
Thank you!

>Solution :

You can use the subtract ufunc with numpy.ufunc.accumulate.

numbers = [100, 70, 25, 10, 5]
result = np.subtract.accumulate(numbers)[1:]
print(result)

Output:

[ 30   5  -5 -10]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading