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 次浏览

开启你的职业生涯

完成该课程的认证

开始
广告