Python Pandas - 如何按小时频率舍入 DateTimeIndex
如需以小时频率舍入 DateTimeIndex,请使用 DateTimeIndex.round() 方法。对于小时频率,使用值为“H”的 freq 参数。
首先,导入所需的库 −
import pandas as pd
创建一个以 5 为周期且频率为 T(即分钟)的 DatetimeIndex −
datetimeindex = pd.date_range('2021-09-29 07:00', periods=5, tz='Australia/Adelaide', freq='35T')
显示 DateTimeIndex −
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)
广告