Data Scientist @ RMOTR

# Sum of Cumulative Sum of a Series

Last updated: December 27th, 2018
In [1]:
import pandas as pd


Create our series from 1 to n:

In [ ]:
n = 5

In [3]:
series = pd.Series(range(1, n+1))
series

Out[3]:
0    1
1    2
2    3
3    4
4    5
dtype: int64

The sequence of numbers (1, 2, 3, 4, 5) is arithmetic and when we are looking for the sum of a sequence, we call it a series. Thanks to Gauss, there is a special formula we can use to find the sum of a series:

$$S = \dfrac{n(n+1)}{2}$$

We can get a cumulative sum over a series using Pandas cumsum() function, so:

In [12]:
series_sum = series.cumsum()
series_sum

Out[12]:
0     1
1     3
2     6
3    10
4    15
dtype: int64

Finally we just need to sum that cumulative sum over our series:

$$\sum_{n=1}^{n} S = \sum_{n=1}^{n} \dfrac{n(n+1)}{2}$$
In [8]:
result = sum(series_sum)
result

Out[8]:
35

Now wrap it in a function:

In [15]:
def sumcumsum(n):
series = pd.Series(range(1, n+1))
series_sum = series.cumsum()
result = sum(series_sum)
print('Given n={}, sum of its cumulative sum is {}'.format(n, result))


Try our function with bigger numbers:

In [16]:
sumcumsum(6)

Given n=6, sum of its cumulative sum is 56

In [17]:
sumcumsum(12)

Given n=12, sum of its cumulative sum is 364

In [18]:
sumcumsum(20)

Given n=20, sum of its cumulative sum is 1540