Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python sum all previous values in array at each index

I have an array:

my_array = [1, 4, 1, 13, 9]

and would like to create a new array that for each index in my_array is the sum of all the previous index values

summed_array = [0, 1, 5, 6, 19]

I tried something like

for ind,i in enumerate(my_array):
    print i, my_array[ind-1]

but can't figure out how to get the summation over all previous values.

like image 431
guest_142535324 Avatar asked Dec 11 '22 19:12

guest_142535324


2 Answers

>>> from numpy import cumsum, ones
>>> a = ones(10)
>>> print(cumsum(a))
array([  1.,   2.,   3.,   4.,   5.,   6.,   7.,   8.,   9.,  10.])
like image 153
MaxNoe Avatar answered Jan 12 '23 17:01

MaxNoe


A pure Python implementation:

def cumilative_sum(lst):
    total, result = 0, []
    for ele in lst:
        result.append(total)
        total += ele
    return result
like image 40
kylieCatt Avatar answered Jan 12 '23 16:01

kylieCatt