Python Pandas - 在 DateTimeIndex 中返回特定時間值對應的索引位置


要返回 DateTimeIndex 中特定時間值對應的索引位置,請使用 DateTimeIndex.indexer_at_time() 方法。

首先,匯入所需的庫 −

import pandas as pd

使用週期為 5、單位為 T(即分鐘)建立 DatetimeIndex −

datetimeindex = pd.date_range('2021-10-30 02:30:50', periods=5, tz='Australia/Adelaide', freq='20T')

顯示 DateTimeIndex −

print("DateTimeIndex...\n", datetimeindex)

顯示特定時間(此處為 03:10:50)的值對應的索引位置 −

print("\nIndex locations of values at particular time of day...\n",
datetimeindex.indexer_at_time('2021-10-30 03:10:50'))

示例

程式碼如下 −

import pandas as pd

# DatetimeIndex with period 5 and frequency as T i.e. minutes
# The timezone is Australia/Adelaide
datetimeindex = pd.date_range('2021-10-30 02:30:50', periods=5, tz='Australia/Adelaide', freq='20T')

# display DateTimeIndex
print("DateTimeIndex...\n", datetimeindex)

# display DateTimeIndex frequency
print("\nDateTimeIndex frequency...\n", datetimeindex.freq)

# display index locations of values at particular time of day i.e. 03:10:50 here
print("\nIndex locations of values at particular time of day...\n",
datetimeindex.indexer_at_time('2021-10-30 03:10:50'))

輸出

這將生成以下程式碼 −

DateTimeIndex...
DatetimeIndex(['2021-10-30 02:30:50+10:30', '2021-10-30 02:50:50+10:30',
'2021-10-30 03:10:50+10:30', '2021-10-30 03:30:50+10:30',
'2021-10-30 03:50:50+10:30'],
dtype='datetime64[ns, Australia/Adelaide]', freq='20T')
DateTimeIndex frequency...
<20 * Minutes>

Index locations of values at particular time of day...
[2]

更新日期:2021 年 10 月 18 日

505 次瀏覽

開啟你的 職業生涯

完成課程即可獲得認證

開始學習
廣告
© . All rights reserved.