Python Pandas - 如何对小时频率的 DateTimeIndex 进行取整运算
若要对小时频率的 DateTimeIndex 执行取整运算,请使用 DateTimeIndex.floor() 方法。对于小时频率,请将 freq 参数与值 ‘H’ 结合使用。
首先,导入需要的库 −
import pandas as pd
使用周期为 5、频率为分钟(即分)创建 DateTimeIndex −
datetimeindex = pd.date_range('2021-09-29 07:20:32.261811624', periods=5, tz='Australia/Adelaide', freq='20min')
显示 DateTimeIndex −
print("DateTimeIndex...\n", datetimeindex)
使用小时频率对 DateTimeIndex 日期执行取整运算时,对于小时频率,我们使用了 'H' −
print("\nPerforming floor operation with hourly frequency...\n", datetimeindex.floor(freq='H'))
示例
代码如下 −
import pandas as pd # DatetimeIndex with period 5 and frequency as min i.e. minutes # timezone is Australia/Adelaide datetimeindex = pd.date_range('2021-09-29 07:20:32.261811624', periods=5, tz='Australia/Adelaide', freq='20min') # display DateTimeIndex print("DateTimeIndex...\n", datetimeindex) # display DateTimeIndex frequency print("DateTimeIndex frequency...\n", datetimeindex.freq) # Floor operation on DateTimeIndex date with hourly frequency # For hourly frequency, we have used 'H' print("\nPerforming floor operation with hourly frequency...\n", datetimeindex.floor(freq='H'))
输出
这将生成以下代码 −
DateTimeIndex... DatetimeIndex(['2021-09-29 07:20:32.261811624+09:30', '2021-09-29 07:40:32.261811624+09:30', '2021-09-29 08:00:32.261811624+09:30', '2021-09-29 08:20:32.261811624+09:30', '2021-09-29 08:40:32.261811624+09:30'], dtype='datetime64[ns, Australia/Adelaide]', freq='20T') DateTimeIndex frequency... <20 * Minutes> Performing floor operation with hourly frequency... DatetimeIndex(['2021-09-29 07:00:00+09:30', '2021-09-29 07:00:00+09:30', '2021-09-29 08:00:00+09:30', '2021-09-29 08:00:00+09:30', '2021-09-29 08:00:00+09:30'], dtype='datetime64[ns, Australia/Adelaide]', freq=None)
广告