guest_142535324
guest_142535324

Reputation: 79

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.

Upvotes: 6

Views: 18876

Answers (7)

Marcos Hernan
Marcos Hernan

Reputation: 1

Another aproach could be:

def cumulative(lst):

    cumulative= []
    for x in range(0, len(cumulative)):
        if x == 0:
            cumulative.append(lst[x])  # Establish the first element
        else:
            cumulative.append(accumulated[x - 1] + lst[x]) # Makes the cumulative sum

return cumulative

Upvotes: 0

Sebastiaan van Baars
Sebastiaan van Baars

Reputation: 123

Hereby another variant of the above using list comperhension:

[sum(my_array[0:i[0]]) for i in enumerate(my_array)]

enumerate is handy to use since it creates tuples containing the index and value at that index

Upvotes: 3

Padraic Cunningham
Padraic Cunningham

Reputation: 180512

itertools.accumulate would work the same as numpy.cumsum:

from operator import add
from itertools import accumulate
from operator import add

def cum_sum(l):
   return accumulate(l, add)

In [22]: list(cum_sum(my_array))
Out[22]: [1, 5, 6, 19, 28]

which will match cumsum exactly.

If you want to ignore the last element:

from operator import add
from itertools import islice, accumulate


def cum_sum(l, take):
   return accumulate(islice(my_array, 0, len(l)-take), add)

In [16]: list(cum_sum(my_array, 1))
Out[16]: [1, 5, 6, 19]

To exactly match your output including the 0 and to work in python2 or 3 you can create a generator function:

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

def cum_sum(l):
    sm = 0
    for ele in l:
        yield sm
        sm += ele

Output:

In [5]: my_array = [1, 4, 1, 13, 9]

In [6]: list(cum_sum(my_array))
Out[6]: [0, 1, 5, 6, 19]

Upvotes: 2

Patrick Yu
Patrick Yu

Reputation: 972

Here is a concise and understandable implementation:

sum = 0

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

for ind,i in enumerate(my_array):
    summed_array[ind] = sum
    sum += my_array[ind]

The code basically starts assigning sum with 0 and putting it into the first index of summed_array, and then it adds each respective index of my_array to sum. Then, it comes back to the for loop and assigns each index of summed_array with the previous sum.

The output would be:

>>> summed_array

[0, 1, 5, 6, 19]

...which is the final expected sums.

EDIT: Thanks @IanAuld, he suggested another method to do it without enumeration and initializing values to 0:

sum = 0

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

for i in my_array:
    summed_array += [sum]
    sum += i

Upvotes: 0

kylieCatt
kylieCatt

Reputation: 11049

A pure Python implementation:

def cumilative_sum(lst):
    total, result = 0, []
    for ele in lst:
        result.append(total)
        total += ele
    return result

Upvotes: 2

user2357112
user2357112

Reputation: 281842

np.cumsum(my_array) - my_array

np.cumsum returns an array of cumulative sums, with each sum going up to and including the corresponding element in the input array. You want to exclude the corresponding elements from the sum, so just subtract them out.

Upvotes: 0

MaxNoe
MaxNoe

Reputation: 15017

>>> from numpy import cumsum, ones
>>> a = ones(10)
>>> print(cumsum(a))
array([  1.,   2.,   3.,   4.,   5.,   6.,   7.,   8.,   9.,  10.])

Upvotes: 10

Related Questions