Python Pandas - 如何对具有小时频率的 DateTimeIndex 执行向上取整操作
要对具有小时频率的 DateTimeIndex 执行向上取整操作,请使用 **DateTimeIndex.ceil()** 方法。对于小时频率,请使用值为“H”的 freq 参数。
首先,导入所需的库 -
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 日期执行向上取整操作。对于小时频率,我们使用了 'H' -
print("\nPerforming ceil operation with hourly frequency...\n", datetimeindex.ceil(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) # Ceil operation on DateTimeIndex date with hourly frequency # For hourly frequency, we have used 'H' print("\nPerforming ceil operation with hourly frequency...\n", datetimeindex.ceil(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 ceil operation with hourly frequency... DatetimeIndex(['2021-09-29 08:00:00+09:30', '2021-09-29 08:00:00+09:30', '2021-09-29 09:00:00+09:30', '2021-09-29 09:00:00+09:30', '2021-09-29 09:00:00+09:30'], dtype='datetime64[ns, Australia/Adelaide]', freq=None)
广告