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

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

Серия Pandas - это одномерный массив ndarray с метками осей. Этикетки не обязательно должны быть уникальными, но должны быть хешируемого типа. Объект поддерживает индексирование как на основе целых чисел, так и на основе меток и предоставляет множество методов для выполнения операций, связанных с индексом.

Pandas Series.asfreq() function is used to convert TimeSeries to specified frequency. The function also provide filling method to pad/backfill missing values.

Syntax: Series.asfreq(freq, method=None, how=None, normalize=False, fill_value=None)

Parameter :
freq : DateOffset object, or string
method : {‘backfill’/’bfill’, ‘pad’/’ffill’}, default None
how : For PeriodIndex only, see PeriodIndex.asfreq
normalize : Whether to reset output index to midnight
fill_value : Value to use for missing values

Returns : converted : same type as caller

Example #1: Use Series.asfreq() function to change the frequency of the given series object.

# importing pandas as pd
import pandas as pd
  
# Creating the Series
sr = pd.Series([11, 21, 8, 18, 65, 18, 32, 10, 5, 32, None])
  
# Create the Index
index_ = pd.date_range("2010-10-09 08:45", periods = 11, freq ="M")
  
# set the index
sr.index = index_
  
# Print the series
print(sr)

Выход :

 2010-12-31 08:45:00 8
2011-01-31 08:45:00 18
2011-02-28 08:45:00 65
2011-03-31 08:45:00 18
2011-04-30 08:45:00 32
2011-05-31 08:45:00 10
2011-06-30 08:45:00 5
2011-07-31 08:45:00 32
2011-08-31 08:45:00 NaN
Freq: M, dtype: float64

Now we will use Series.asfreq() function to change the frequency of the given series object to quarterly.

# change to quarterly frequency
result = sr.asfreq(freq = "Q")
  
# Print the result
print(result)

Выход :

 2010-12-31 08:45:00 8
2011-03-31 08:45:00 18
2011-06-30 08:45:00 5
Частота: Q-DEC, dtype: float64

As we can see in the output, the Series.asfreq() function has successfully changed the frequency of the given series object.
 
Example #2 : Use Series.asfreq() function to change the yearly frequency of the given series object to the batches of 3 years.

# importing pandas as pd
import pandas as pd
  
# Creating the Series
sr = pd.Series([11, 21, 8, 18, 65, 18, 32, 10, 5, 32, None])
  
# Create the Index
# apply yearly frequency
index_ = pd.date_range("2010-10-09 08:45", periods = 11, freq ="Y")
  
# set the index
sr.index = index_
  
# Print the series
print(sr)

Выход :

 2010-12-31 08:45:00 11.0
2011-12-31 08:45:00 21.0
2012-12-31 08:45:00 8.0
2013-12-31 08:45:00 18.0
2014-12-31 08:45:00 65.0
2015-12-31 08:45:00 18.0
2016-12-31 08:45:00 32.0
2017-12-31 08:45:00 10.0
2018-12-31 08:45:00 5.0
2019-12-31 08:45:00 32.0
2020-12-31 08:45:00 NaN
Частота: A-DEC, dtype: float64

Now we will use Series.asfreq() function to change the yearly frequency of the given series object to the batches of 3 years.

# apply year batch frequency
result = sr.asfreq(freq = "3Y")
  
# Print the result
print(result)

Выход :

 2010-12-31 08:45:00 11.0
2013-12-31 08:45:00 18.0
2016-12-31 08:45:00 32.0
2019-12-31 08:45:00 32.0
Частота: 3A-DEC, dtype: float64

As we can see in the output, the Series.asfreq() function has successfully changed the frequency of the given series object.

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

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