Python Pandas - 如何以每小时的频率对 DateTimeIndex 执行地板操作

要以每小时的频率对 DateTimeIndex 执行地板运算,请使用方法。对于每小时频率,请使用值为'H'freq参数。DateTimeIndex.floor()

首先,导入所需的库 -

import pandas as pd

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

datetimeindex = pd.date_range('2021-09-29 07:20:32.261811624', periods=5,
tz='Australia/Adelaide', freq='20min')

显示 DateTimeInde -

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)

猜你喜欢