Python Pandas - 如何對小時頻率的 DateTimeIndex 進行取整運算


若要對小時頻率的 DateTimeIndex 執行取整運算,請使用 DateTimeIndex.floor() 方法。對於小時頻率,請將 freq 引數與值 ‘H’ 結合使用。

首先,匯入需要的庫 −

import pandas as pd

使用週期為 5、頻率為分鐘(即分)建立 DateTimeIndex −

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

顯示 DateTimeIndex −

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)

更新於:2021 年 10 月 19 日

90 次瀏覽

職業生涯 KICKSTART

完成課程獲得認證

開始吧
廣告
© . All rights reserved.