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.
|
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.
|
Exit:
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,