Python | Pandas Series.pct_change ()

NumPy | Python Methods and Functions

First, the n (n = period) values ​​are always NaN because there is no previous value to calculate the change.

Syntax: Series.pct_change(periods=1, fill_method = `pad`, limit = None)

Parameters:
periods: Defines gap between current and previous value. Default is 1
fill_method: Defines method used to handle null values ​​
limit: Number of consecutive NaN values ​​to fill before stopping.

Return type: Numeric series with percentage change

Example # 1:

In this method A series is created from a Python list using Pandas Series () . The series does not contain a null value, so pct_change () is called directly with a default value for the period parameter of 1.

# pandas module import

import pandas as pd 

 
# importing the numpy module

import numpy as np 

  
# create a list

list = [ 10 , 14 , 20 , 25 , 12.5 , 13 , 0 , 50 ]

 
# create a series

series = pd.Series ( list )

 
# calling method

result = series.pct_change ()

 
# display
result

Exit:

 0 NaN 1 0.400000 2 0.428571 3 0.250000 4 -0.5000 00 5 0.040000 6 -1.000000 7 inf dtype: float64 

As shown in the output, the first n values ​​are always NaN. The remaining values ​​are equal to the percentage change in the old values ​​and are stored in the same position as a number of callers. 
Note. Since the second last value was 0, the percentage change is inf. Inf means infinity. 
Using the formula, pct_change = x-0/0 = Infinte

Example # 2: Handling null values ​​

In this example, some null values are also created using Numpy`s np.nan method and passed to a list. & # 39;  bfill & # 39; passed to fill_method bfill stands for Back fill and will fill zero values ​​with values ​​in their next position.

# pandas module import

import pandas as pd 

 
# numpy module import

import numpy as np 

 
# create a list

list = [ 10 , np.nan, 14 , 20 , 25 , 12.5 , 13 , 0 , 50 ]

 
# create series

series = pd.Series ( list )

 
# calling method

result = series.pct_change (fill_method = `bfill` )

  
# display
result

Exit:

0 NaN 1 0.400000 2 0.000000 3 0.428571 4 0.250000 5 -0.500000 6 0.040000 7 -1.000000 8 inf dtype: float64

As you can see from the output, the value at position 1 is 40 because the NaN has been replaced by 14. Therefore, (14-10 / 10) * 100 = 40. The next value is 0 because the percentage change in 14 and 14 is 0,





Get Solution for free from DataCamp guru