Python Pandas - 创建闭区间并检查端点的存在


要创建闭区间,请使用 **pandas.Interval()** 并设置 closed 参数。要检查两个端点的存在,请使用 in 属性。

首先,导入所需的库:

import pandas as pd

使用值为“both”的“closed”参数设置闭区间。闭区间(在数学中用方括号表示)包含其端点,例如闭区间 [0, 5] 的特征是 0 <= x <= 5

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

显示区间

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

检查区间中是否存在元素。这表明 closed = both 包含其端点

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)

示例

以下是代码:

Open Compiler
import pandas as pd # Closed interval set using the "closed" parameter with value "both" # A closed interval (in mathematics denoted by square brackets) contains its endpoints, # i.e. the closed interval [0, 5] is characterized by the conditions 0 <= x <= 5. interval = pd.Interval(left=0, right=20, closed='both') # 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 = both contains its endpoints 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日

272 次浏览

启动您的 职业生涯

完成课程获得认证

开始学习
广告