Pandas Series dt.floor() | Round DateTime Values to Nearest Frequency
Last Updated :
07 Feb, 2024
The dt.floor() method performs floor operation on the data to the specified frequency.
This is useful when we want to round down the DateTime data to a specific frequency level, such as hourly (‘H’), daily (‘D’), monthly (‘M’), etc.
Example
Python3
import pandas as pd
sr = pd.Series([ '2012-12-31 08:45' , '2019-1-1 12:30' , '2008-02-2 10:30' ,
'2010-1-1 09:25' , '2019-12-31 00:00' ])
idx = [ 'Day 1' , 'Day 2' , 'Day 3' , 'Day 4' , 'Day 5' ]
sr.index = idx
sr = pd.to_datetime(sr)
result = sr.dt.floor(freq = 'D' )
print (result)
|
Output:
Syntax
Syntax: Series.dt.floor(floor)Â
ParameterÂ
- freq : The frequency level to floor the index to
Returns: DatetimeIndex, TimedeltaIndex, or Series
How to Round Down DateTime Objects to a Specified Frequency
To round down DateTime objects in Pandas Series to a specified frequency we use the Series.dt.floor method of the Pandas library in Python.
Let us understand it better with an example:
Example:
Use the Series dt.floor() function to floor the DateTime data of the given Series object to the specified frequency.
Python3
import pandas as pd
sr = pd.Series(pd.date_range( '2012-12-31 09:45' , periods = 5 , freq = 'T' ,
tz = 'Asia / Calcutta' ))
idx = [ 'Day 1' , 'Day 2' , 'Day 3' , 'Day 4' , 'Day 5' ]
sr.index = idx
print (sr)
|
Output
Python3
result = sr.dt.floor(freq = 'H' )
print (result)
|
Output :
As we can see in the output, the Series.dt.floor() function has successfully floored the DateTime values in the given series object to the specified frequency.
Share your thoughts in the comments
Please Login to comment...