首页 文章资讯内容详情

Python Pandas - 如何以每小时的频率舍入 DateTimeIndex

2026-06-03 1 花语

要以每小时的频率舍入DateTimeIndex,请使用方法。对于每小时频率,使用值为“H”的freq 参数。DateTimeIndex.round()

首先,导入所需的库-

import pandas as pd

创建一个日期时间索引,周期为5,频率为T即分钟-

datetimeindex = pd.date_range(2021-09-29 07:00, periods=5, tz=Australia/Adelaide, freq=35T)

显示日期时间索引-

print("DateTimeIndex...\n", datetimeindex)

以每小时的频率对DateTimeIndex日期进行舍入操作。对于每小时频率,我们使用了“H”-

print("\nPerforming round operation with hourly frequency...\n", datetimeindex.round(freq=H))

示例

以下是代码-

import pandas as pd #DatetimeIndexwithperiod5andfrequencyasTi.e.minutes #timezoneisAustralia/Adelaide datetimeindex = pd.date_range(2021-09-29 07:00, periods=5, tz=Australia/Adelaide, freq=35T) #display print("DateTimeIndex...\n", datetimeindex) #gettingthehour res = datetimeindex.hour #display only the hour print("\nThe hour from DateTimeIndex...\n", res) #RoundoperationonDateTimeIndexdatewithhourlyfrequency # For hourly frequency, we have used H print("\nPerforming round operation with hourly frequency...\n", datetimeindex.round(freq=H))输出结果

这将产生以下代码-

DateTimeIndex... DatetimeIndex([2021-09-29 07:00:00+09:30, 2021-09-29 07:35:00+09:30, 2021-09-29 08:10:00+09:30, 2021-09-29 08:45:00+09:30, 2021-09-29 09:20:00+09:30], dtype=datetime64[ns, Australia/Adelaide], freq=35T) The hour from DateTimeIndex... Int64Index([7, 7, 8, 8, 9], dtype=int64) Performing round operation with hourly frequency... DatetimeIndex([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 09:00:00+09:30, 2021-09-29 09:00:00+09:30], dtype=datetime64[ns, Australia/Adelaide], freq=None)