Python | Панды Series.pct_change ()

Опубликовано: 28 Марта, 2022

Pandas pct_change() method is applied on series with numeric data to calculate Percentage change after n number of elements. By default, it calculates percentage change of current element from the previous element. (Current-Previous/Previous) * 100.

Во-первых, значения n (n = период) всегда равны NaN , поскольку нет предыдущего значения для расчета изменения.

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

Пример №1:

In this method, a Series is created from Python list using Pandas Series(). The series doesn’t contain any null value and hence pct_change() method is called directly with default value of period parameter, that is 1.

# importing pandas module 
import pandas as pd 
    
# importing numpy module 
import numpy as np 
    
# creating list
list = [10, 14, 20, 25, 12.5, 13, 0, 50]
  
# creating series
series = pd.Series(list)
  
# calling method
result = series.pct_change()
  
# display
result

Выход:

0 NaN
1 0,400000
2 0,428571
3 0,250000
4 -0,500000
5 0,040000
6 -1,000000
7 инф
dtype: float64

Как показано на выходе, первые n значений всегда равны NaN. Остальные значения равны процентному изменению старых значений и сохраняются в той же позиции, что и ряд вызывающих.
Примечание. Поскольку второе последнее значение было 0, процентное изменение равно бесконечности. inf означает бесконечность.
Используя формулу, pct_change = x-0/0 = Infinte


Пример # 2: Обработка нулевых значений

In this example, some null values are also created using Numpy’s np.nan method and passed to the list. ‘bfill‘ is passed to fill_method. bfill stands for Back fill and will fill Null values with values at their very next position.

# importing pandas module 
import pandas as pd 
    
# importing numpy module 
import numpy as np 
    
# creating list
list =[10, np.nan, 14, 20, 25, 12.5, 13, 0, 50]
  
# creating series
series = pd.Series(list)
  
# calling method
result = series.pct_change(fill_method ="bfill")
  
# display
result

Выход:

0 NaN
1 0,400000
2 0,000000
3 0,428571
4 0,250000
5 -0,500000
6 0,040000
7 -1,000000
8 инф
dtype: float64

Как видно из выходных данных, значение в позиции 1 равно 40, потому что NaN было заменено на 14. Следовательно, (14-10 / 10) * 100 = 40. Следующее значение равно 0, потому что процентное изменение в 14 и 14 равно 0. .

Внимание компьютерщик! Укрепите свои основы с помощью базового курса программирования Python и изучите основы.

Для начала подготовьтесь к собеседованию. Расширьте свои концепции структур данных с помощью курса Python DS. А чтобы начать свое путешествие по машинному обучению, присоединяйтесь к курсу Машинное обучение - базовый уровень.