Python Pandas - Check if the interval is open on the right side

In Pandas, you can check if an interval is open on the right side using the open_right property. An interval is open on the right when it doesn't include its right endpoint.

Understanding Interval Closures

Pandas intervals can have different closure types ?

  • closed='both' - includes both endpoints [5, 20]
  • closed='left' - includes only left endpoint [5, 20)
  • closed='right' - includes only right endpoint (5, 20]
  • closed='neither' - excludes both endpoints (5, 20)

Checking Right-Open Intervals

The open_right property returns True when the interval excludes its right endpoint ?

import pandas as pd

# Create different types of intervals
interval_neither = pd.Interval(5, 20, closed='neither')  # (5, 20)
interval_left = pd.Interval(5, 20, closed='left')        # [5, 20)
interval_right = pd.Interval(5, 20, closed='right')      # (5, 20]
interval_both = pd.Interval(5, 20, closed='both')        # [5, 20]

print("Interval (5, 20) - open_right:", interval_neither.open_right)
print("Interval [5, 20) - open_right:", interval_left.open_right)
print("Interval (5, 20] - open_right:", interval_right.open_right)
print("Interval [5, 20] - open_right:", interval_both.open_right)
Interval (5, 20) - open_right: True
Interval [5, 20) - open_right: True
Interval (5, 20] - open_right: False
Interval [5, 20] - open_right: False

Complete Example

Here's a comprehensive example showing interval properties ?

import pandas as pd

# Create an open interval
interval = pd.Interval(5, 20, closed='neither')

print("Interval:", interval)
print("Left bound:", interval.left)
print("Right bound:", interval.right)
print("Length:", interval.length)
print("Open on right side:", interval.open_right)
print("Open on left side:", interval.open_left)
Interval: (5, 20)
Left bound: 5
Right bound: 20
Length: 15
Open on right side: True
Open on left side: True

Practical Use Cases

Right-open intervals are useful for data binning and time ranges ?

import pandas as pd

# Age groups with right-open intervals
age_groups = [
    pd.Interval(0, 18, closed='left'),   # [0, 18) - children
    pd.Interval(18, 65, closed='left'),  # [18, 65) - adults
    pd.Interval(65, 100, closed='left')  # [65, 100) - seniors
]

for group in age_groups:
    print(f"Age group {group} - open_right: {group.open_right}")
Age group [0, 18) - open_right: True
Age group [18, 65) - open_right: True
Age group [65, 100) - open_right: True

Conclusion

Use the open_right property to check if an interval excludes its right endpoint. This is particularly useful for data binning and creating non-overlapping ranges.

Updated on: 2026-03-26T18:05:27+05:30

199 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements