Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find the cumulative sum of numbers in a list?

time_interval = [4, 6, 12] 

I want to sum up the numbers like [4, 4+6, 4+6+12] in order to get the list t = [4, 10, 22].

I tried the following:

t1 = time_interval[0] t2 = time_interval[1] + t1 t3 = time_interval[2] + t2 print(t1, t2, t3)  # -> 4 10 22 
like image 576
user2259323 Avatar asked Apr 08 '13 21:04

user2259323


People also ask

How do you do a cumulative sum list in Python?

We declare an empty list cum_list to which we will append elements to form the cumulative sum list. Initialize a sum variable sm=0. Start iterating over the input list, with each iteration we increment the sum value to previous value+ the current element. On each iteration, the sum value is appended to the cum_list.

How do you find the cumulative summation of values for each row in Python?

The cumsum() method returns a DataFrame with the cumulative sum for each row. The cumsum() method goes through the values in the DataFrame, from the top, row by row, adding the values with the value from the previous row, ending up with a DataFrame where the last row contains the sum of all values for each column.

What is meant by cumulative sum?

Cumulative sums, or running totals, are used to display the total sum of data as it grows with time (or any other series or progression). This lets you view the total contribution so far of a given measure against time.


2 Answers

If you're doing much numerical work with arrays like this, I'd suggest numpy, which comes with a cumulative sum function cumsum:

import numpy as np  a = [4,6,12]  np.cumsum(a) #array([4, 10, 22]) 

Numpy is often faster than pure python for this kind of thing, see in comparison to @Ashwini's accumu:

In [136]: timeit list(accumu(range(1000))) 10000 loops, best of 3: 161 us per loop  In [137]: timeit list(accumu(xrange(1000))) 10000 loops, best of 3: 147 us per loop  In [138]: timeit np.cumsum(np.arange(1000)) 100000 loops, best of 3: 10.1 us per loop 

But of course if it's the only place you'll use numpy, it might not be worth having a dependence on it.

like image 105
askewchan Avatar answered Oct 22 '22 04:10

askewchan


In Python 2 you can define your own generator function like this:

def accumu(lis):     total = 0     for x in lis:         total += x         yield total  In [4]: list(accumu([4,6,12])) Out[4]: [4, 10, 22] 

And in Python 3.2+ you can use itertools.accumulate():

In [1]: lis = [4,6,12]  In [2]: from itertools import accumulate  In [3]: list(accumulate(lis)) Out[3]: [4, 10, 22] 
like image 26
Ashwini Chaudhary Avatar answered Oct 22 '22 03:10

Ashwini Chaudhary