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

To create a closed time interval in Pandas, use the pandas.Interval() constructor with the closed='both' parameter. A closed interval contains its endpoints, meaning both boundary values are included in the interval.

Creating a Closed Interval

First, import the required library ?

import pandas as pd

Create a closed interval using the closed='both' parameter ?

import pandas as pd

# Create a closed interval from 0 to 20
interval = pd.Interval(left=0, right=20, closed='both')

# Display the interval
print("Interval...")
print(interval)

# Display the interval length
print("\nInterval length:")
print(interval.length)
Interval...
[0, 20]

Interval length:
20

Checking Endpoint Existence

Use the in operator to check if endpoints exist in the interval ?

import pandas as pd

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

# Check for existence of endpoints
print("Left endpoint (0) exists in interval?", 0 in interval)
print("Right endpoint (20) exists in interval?", 20 in interval)

# Check for values inside and outside the interval
print("Value 10 exists in interval?", 10 in interval)
print("Value 25 exists in interval?", 25 in interval)
Left endpoint (0) exists in interval? True
Right endpoint (20) exists in interval? True
Value 10 exists in interval? True
Value 25 exists in interval? False

Interval Types Comparison

Closed Parameter Mathematical Notation Includes Left Includes Right
'both' [0, 20] Yes Yes
'left' [0, 20) Yes No
'right' (0, 20] No Yes
'neither' (0, 20) No No

Complete Example

import pandas as pd

# Create different types of intervals
closed_both = pd.Interval(0, 20, closed='both')
closed_left = pd.Interval(0, 20, closed='left')

print("Closed interval (both endpoints):", closed_both)
print("Left-closed interval:", closed_left)

print("\nTesting endpoint 0:")
print("In closed_both:", 0 in closed_both)
print("In closed_left:", 0 in closed_left)

print("\nTesting endpoint 20:")
print("In closed_both:", 20 in closed_both)
print("In closed_left:", 20 in closed_left)
Closed interval (both endpoints): [0, 20]
Left-closed interval: [0, 20)

Testing endpoint 0:
In closed_both: True
In closed_left: True

Testing endpoint 20:
In closed_both: True
In closed_left: False

Conclusion

Use pd.Interval() with closed='both' to create intervals that include both endpoints. The in operator efficiently checks element existence within the interval boundaries.

Updated on: 2026-03-26T17:48:10+05:30

397 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements