Python Pandas - 如何以每小时的频率舍入 DateTimeIndex
要以每小时的频率舍入 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输出结果# DatetimeIndex with period 5 and frequency as T i.e. minutes
# timezone is Australia/Adelaide
datetimeindex = pd.date_range('2021-09-29 07:00', periods=5, tz='Australia/Adelaide', freq='35T')
# display
print("DateTimeIndex...\n", datetimeindex)
# getting the hour
res = datetimeindex.hour
# display only the hour
print("\nThe hour from DateTimeIndex...\n", res)
# Round operation on DateTimeIndex date with hourly frequency
# 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)
以上是 Python Pandas - 如何以每小时的频率舍入 DateTimeIndex 的全部内容, 来源链接: utcz.com/z/322618.html