Pandas Tutorial Pandas References

Pandas Series - cumprod() function



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

Syntax

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

Parameters

axis Optional. Specify {0 or 'index', 1 or 'columns'}. If 0 or 'index', cumulative products are generated for each column. If 1 or 'columns', cumulative products 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 product scalar or Series.

Example: using cumprod() on a Series

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

import pandas as pd
import numpy as np

x = pd.Series([1, 2, 3, 4, 5, 6, 7])

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

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

The output of the above code will be:

The Series contains:
0    1
1    2
2    3
3    4
4    5
5    6
6    7
dtype: int64

x.cumprod() returns:
0       1
1       2
2       6
3      24
4     120
5     720
6    5040
dtype: int64

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

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

import pandas as pd
import numpy as np

report = pd.DataFrame({
  "GDP": [1.02, 1.03, 1.04, 0.98],
  "GNP": [1.05, 0.99, np.nan, 1.04],
  "HDI": [1.02, 1.01, 1.02, 1.03]},
  index= ["Q1", "Q2", "Q3", "Q4"]
)

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

#cumulative product on 'GDP' series
print("report['GDP'].cumprod() returns:")
print(report['GDP'].cumprod(),"\n")

The output of the above code will be:

The DataFrame is:
     GDP   GNP   HDI
Q1  1.02  1.05  1.02
Q2  1.03  0.99  1.01
Q3  1.04   NaN  1.02
Q4  0.98  1.04  1.03 

report['GDP'].cumprod() returns:
Q1    1.020000
Q2    1.050600
Q3    1.092624
Q4    1.070772
Name: GDP, dtype: float64 

❮ Pandas Series - Functions