Python Pandas - Create a closed time interval and check for existence of both the endpoints



To create a closed time interval, use the pandas.Interval() and set the closed parameter. To check for existence of both the endpoints, use the in property.

At first, import the required libraries −

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)

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)

Example

Following is the code

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)

Output

This will produce the following code

Interval...
[0, 20]

Interval length...
20


Advertisements