6

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.

1
  • 3
    you can use np.cumsum Commented Nov 24, 2015 at 1:12

7 Answers 7

10
>>> from numpy import cumsum, ones
>>> a = ones(10)
>>> print(cumsum(a))
array([  1.,   2.,   3.,   4.,   5.,   6.,   7.,   8.,   9.,  10.])
Sign up to request clarification or add additional context in comments.

1 Comment

@IanAuld: It's in the tags, so they're probably already using it.
3

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

Comments

2

A pure Python implementation:

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

3 Comments

When the linear-time solution is so easy, please don't use quadratic-time solutions.
@user2357112, how is this solution quadratic-time?
@JohnK: See the edit history. It was quadratic time when I left that comment.
2

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]

Comments

0
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.

Comments

0

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

2 Comments

What's concise about creating a separate list of 0's and using enumerate and indexing instead of the values in the list directly?
@IanAuld Yeah, neat suggestion! Thanks!
0

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

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.