Python Pandas - 在DateTimeIndex中返回特定時間段內值的索引位置(包括起始時間)
要在DateTimeIndex中返回特定時間段內值的索引位置,可以使用**DateTimeIndex.indexer_between_time()**方法。將**include_start**引數設定為**True**以包含起始時間。
首先,匯入所需的庫:
import pandas as pd
建立一個週期為7,頻率為T(即分鐘)的DatetimeIndex:
datetimeindex = pd.date_range('2021-10-30 02:30:50', periods=7, tz='Australia/Adelaide', freq='20T')
顯示DateTimeIndex:
print("DateTimeIndex...\n", datetimeindex)顯示特定時間段內值的索引位置。“start_time”設定為'02:30:50',“end_time”設定為'03:20:50'。將include_start引數設定為True:
print("\nIndex locations of values between particular time of day...\n",
datetimeindex.indexer_between_time('03:10:50','03:50:50', include_start = True))示例
以下是程式碼:
import pandas as pd
# DatetimeIndex with period 7 and frequency as T i.e. minutes
# The timezone is Australia/Adelaide
datetimeindex = pd.date_range('2021-10-30 02:30:50', periods=7, 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'))
# display index locations of values between particular time of day
# The "start_time" is set '02:30:50' and "end_time" '03:20:50'
print("\nIndex locations of values between particular time of day...\n",
datetimeindex.indexer_between_time('03:10:50','03:50:50', include_start = True))輸出
這將生成以下程式碼:
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', '2021-10-30 04:10:50+10:30', '2021-10-30 04:30:50+10:30'], dtype='datetime64[ns, Australia/Adelaide]', freq='20T') DateTimeIndex frequency... <20 * Minutes> Index locations of values at particular time of day... [2] Index locations of values between particular time of day... [2 3 4]
廣告
資料結構
網路
關係型資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP