Pandas Tutorial Pandas References

Pandas Series - cumsum() function



The Pandas Series cumsum() function computes cumulative sum over a DataFrame or Series axis and returns a DataFrame or Series of the same size containing the cumulative sum.

Syntax

Series.cumsum(axis=None, skipna=True)

Parameters

axis Optional. Specify {0 or 'index', 1 or 'columns'}. If 0 or 'index', cumulative sums are generated for each column. If 1 or 'columns', cumulative sums are generated for each row. Default: 0
skipna Optional. Specify True to exclude NA/null values when computing the result. Default is True.

Return Value

Return cumulative sum of scalar or Series.

Example: using cumsum() on a Series

In the example below, the cumsum() function is used to get the cumulative sum of values of a given series.

import pandas as pd
import numpy as np

x = pd.Series([10, 11, 12, 9, 13, 12, 10])

print("The Series contains:")
print(x)

#cumulative sum of values in the series
print("\nx.cumsum() returns:")
print(x.cumsum())

The output of the above code will be:

The Series contains:
0    10
1    11
2    12
3     9
4    13
5    12
6    10
dtype: int64

x.cumsum() returns:
0    10
1    21
2    33
3    42
4    55
5    67
6    77
dtype: int64

Example: using cumsum() on selected series in a DataFrame

Similarly, the cumsum() function can be applied on selected series/column of a given DataFrame. Consider the following example.

import pandas as pd
import numpy as np

info = pd.DataFrame({
  "Salary": [25, 24, 30, 28, 25],
  "Bonus": [10, 8, 9, np.nan, 9],
  "Others": [5, 4, 7, 5, 8]},
  index= ["2015", "2016", "2017", "2018", "2019"]
)

print("The DataFrame is:")
print(info,"\n")

#cumulative sum on 'Salary' series
print("info['Salary'].cumsum() returns:")
print(info['Salary'].cumsum(),"\n")

The output of the above code will be:

The DataFrame is:
      Salary  Bonus  Others
2015      25   10.0       5
2016      24    8.0       4
2017      30    9.0       7
2018      28    NaN       5
2019      25    9.0       8 

info['Salary'].cumsum() returns:
2015     25
2016     49
2017     79
2018    107
2019    132
Name: Salary, dtype: int64 

❮ Pandas Series - Functions

5