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)

更新於: 18-Oct-2021

727 次瀏覽

開啟你的 職業生涯

完成該課程以獲得認證

開始
廣告
© . All rights reserved.