Python Pandas - 创建半开时间区间并检查端点是否存在


要创建一个半开时间区间,请使用 pandas.Interval() 并将 closed 参数设置为 left。要检查端点是否存在,请使用此 in 属性。

首先,导入所需的库 -

import pandas as pd

半开区间使用带有值 “left” 的 “closed” 参数设置。当 closed='left',半开区间 [0, 5) 由 0 <= x < 5 描述。

interval = pd.Interval(left=0, right=20, closed='left')

显示区间

print("Interval...\n",interval)

检查区间中元素是否存在。这表明 closed = left 仅包含最左侧的端点

print("\nThe left-most element exists in the Interval? = \n",0 in interval)
print("\nThe right-most element exists in the Interval? = \n",20 in interval)

示例

以下为代码

import pandas as pd

# Half-Open interval set using the "closed" parameter with value "left"
# Half-open i.e. [0, 5) is described by 0 <= x < 5 when closed='left'
interval = pd.Interval(left=0, right=20, closed='left')

# display the interval
print("Interval...\n",interval)

# display the interval length
print("\nInterval length...\n",interval.length)

# check for the existence of an element in an Interval
# This shows that closed = left contain only the left-most endpoint
print("\nThe left-most element exists in the Interval? = \n",0 in interval)
print("\nThe right-most element exists in the Interval? = \n",20 in interval)

输出

这将生成以下代码

Interval...
[0, 20)

Interval length...
20

更新于: 2021 年 10 月 20 日

289 次查看

开始你的 职业生涯

完成课程,获得认证

开始
广告