Python | Pandas Series.asfreq()
Last Updated :
27 Feb, 2019
Pandas series is a One-dimensional ndarray with axis labels. The labels need not be unique but must be a hashable type. The object supports both integer- and label-based indexing and provides a host of methods for performing operations involving the index.
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.
import pandas as pd
sr = pd.Series([ 11 , 21 , 8 , 18 , 65 , 18 , 32 , 10 , 5 , 32 , None ])
index_ = pd.date_range( '2010-10-09 08:45' , periods = 11 , freq = 'M' )
sr.index = index_
print (sr)
|
Output :
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.
result = sr.asfreq(freq = 'Q' )
print (result)
|
Output :
2010-12-31 08:45:00 8
2011-03-31 08:45:00 18
2011-06-30 08:45:00 5
Freq: 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.
import pandas as pd
sr = pd.Series([ 11 , 21 , 8 , 18 , 65 , 18 , 32 , 10 , 5 , 32 , None ])
index_ = pd.date_range( '2010-10-09 08:45' , periods = 11 , freq = 'Y' )
sr.index = index_
print (sr)
|
Output :
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
Freq: 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.
result = sr.asfreq(freq = '3Y' )
print (result)
|
Output :
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
Freq: 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.
Share your thoughts in the comments
Please Login to comment...