Python | Pandas series.cumprod () to find the cumulative product of the Series

Pandas Series.cumprod() is used to find the cumulative product of a series. In the cumulative product, the length of the returned series is the same as that of the input series, and each element is equal to the product of the current and all previous values.

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

Parameters:
axis: 0 or 'index' for row wise operation and 1 or 'columns' for column wise operation
skipna: Skips NaN addition for elements after the very next one if True.

Return type: Series

Example # 1:

This example creates a series from a Python list. The list also contains a Null value, and the skipna parameter remains the default, which is True.

Exit :

 0 2.0 1 20.0 2 NaN 3 80.0 4 240.0 5 0.0 6 0.0 dtype: float64 

Explanation: Cumprod — it is the multiplication of the current and all previous values. Therefore, the first element is always equal to the first of the callers.

 2 20 (2 x 10) NaN (20 x NaN = NaN, Anything multiplied with NaN returns NaN) 80 (20 x 4) 240 (80 x 3) 0 (240 x 0) 0 (0 x 1) 

Example # 2: saving skipna = False

In this example, a series is created in the same as in the above example. But the skipna parameter remains False. Therefore, NULL values ​​will not be ignored and they will be compared each time they are found.

# pandas module import

import pandas as pd 

  
# numpy module import

import numpy as np 

  
# list values ​​

values ​​ = [ 2 , 10 , np.nan, 4 , 3 , 0 , 1

 
# create a series from the list

series = pd.Series (values) 

 
# calling method

cumprod = series.cumprod () 

 
# display
cumprod

# pandas module import

import pandas as pd 

 
# numpy module import

import numpy as np 

 
# compiling a list of values ​​

values ​​ = [ 9 , 4 , 33 , np.nan, 0 , 1 , 76 , 5

 
# create a series from the list

series = pd.Series (values) 

 
# calling method

cumprod = series.cumprod (skipna = False

 
# display
cumprod 

Exit:

 0 9.0 1 36.0 2 1188.0 3 NaN 4 NaN 5 NaN 6 NaN 7 NaN dtype: float64 

Explanation: As in the previous example, the product of the current and all previous values ​​was returned at each position. Since the multiplication of NaN by anything is also NaN, and the skipna parameter was stored to False, hence all values ​​after NaN appear are also NaN.





Get Solution for free from DataCamp guru