Open In App

Pandas Series dt.floor() | Round DateTime Values to Nearest Frequency

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




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.




# importing pandas as pd
import pandas as pd
  
# Creating the Series
sr = pd.Series(pd.date_range('2012-12-31 09:45', periods = 5, freq = 'T',
                            tz = 'Asia / Calcutta'))
  
# Creating the index
idx = ['Day 1', 'Day 2', 'Day 3', 'Day 4', 'Day 5']
  
# set the index
sr.index = idx
  
# Print the series
print(sr)

Output




# floor to hourly frequency
result = sr.dt.floor(freq = 'H')
  
# print the result
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.


Article Tags :