How does the series.cumprod() method work in Pandas?

PandasServer Side ProgrammingProgramming

By using the cumprod() method in the Pandas Series constructor we can find out the cumulative products of the elements of a given series object.

The cumprod() method returns a series of the same length as the original input series object, containing the cumulative product.

And there are three parameters in the cumprod() method which are “axis”, “skipna” and additional keywords. The “skipna” parameter is used to exclude the missing values by default, if you want to include those missing values, then set the skipna parameter to “False”.

Example 1

# importing required packages
import pandas as pd
import numpy as np

# create a pandas Series object
series = pd.Series([5,np.nan,-2,10])
print(series)

print("Cumulative product: ",series.cumprod())

Explanation

In the following example, we are calculating the cumulative product of the Series. It returns a Series without changing the first element and the second element is the product of the first and second element, and the third element is the product of the second and third element and goes like this.

Output

0  5.0
1  NaN
2 -2.0
3 10.0
dtype: float64

Cumulative product:
0    5.0
1    NaN
2  -10.0
3 -100.0
dtype: float64

By default the cumprod() method doesn’t include the Nan values while execution, so the Nan value at 1st location remains the same.

Example 2

# importing required packages
import pandas as pd
import numpy as np

# create a pandas Series object
series = pd.Series([5,-3,np.nan,11,6])
print(series)

print("Cumulative product including NA: ",series.cumprod(skipna=False))

Explanation

In this example, we calculated the cumprod() method by setting the skipna value to False. This means it won’t ignore the NA/null values while executing.

Output

0  5.0
1 -3.0
2  NaN
3 11.0
4  6.0
dtype: float64

Cumulative product including NA:
0   5.0
1 -15.0
2   NaN
3   NaN
4   NaN
dtype: float64

In the above output block, we can see the cumulative product of the given series object. After index position “2” there we can see only the Nan values which is due to the product between the null value and any other value will be null values only.

raja
Updated on 09-Mar-2022 08:07:55

Advertisements