Python Pandas IntervalIndex - 如果一個標籤在多個時間間隔內,獲取所有相關時間間隔內的位置


如果一個標籤在多個時間間隔內,可以利用 Pandas 中的 get_loc() 方法獲取所有相關時間間隔內的位置。

首先,匯入所需的庫 −

import pandas as pd

建立兩個 Interval 物件。使用值 "both" 設定 closed 引數來設定封閉時間間隔

interval1 = pd.Interval(50, 75)
interval2 = pd.Interval(75, 90)
interval3 = pd.Interval(50, 90)

從這三個時間間隔建立 IntervalIndex −

index = pd.IntervalIndex([interval1, interval2, interval3])

如果一個標籤在多個時間間隔內,獲取所有相關時間間隔內的位置 −

print("\nGet the locations of all the relevant interval...\n",index.get_loc(65))

示例

以下是程式碼 −

import pandas as pd

# Create two Interval objects
# Closed intervals set using the "closed" parameter with value "both"
interval1 = pd.Interval(50, 75)
interval2 = pd.Interval(75, 90)
interval3 = pd.Interval(50, 90)

# display the intervals
print("Interval1...\n",interval1)
print("Interval2...\n",interval2)
print("Interval3...\n",interval3)

# Create IntervalIndex from the three intervals
index = pd.IntervalIndex([interval1, interval2, interval3])

# Get the locations of all the relevant interval if a label is in several intervals
print("\nGet the locations of all the relevant interval...\n",index.get_loc(65))

輸出

將會生成以下輸出 −

Interval1...
(50, 75]
Interval2...
(75, 90]
Interval3...
(50, 90]

Get the locations of all the relevant interval...
[ True False True]

更新時間: 18-Oct-2021

149 次瀏覽

開啟你的職業生涯

完成該課程的認證

開始
廣告
© . All rights reserved.