New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ENH: Add a length attribute to Interval and IntervalIndex #18789

jschendel opened this Issue Dec 15, 2017 · 3 comments


None yet
3 participants

jschendel commented Dec 15, 2017

Problem description

Seems like a pretty standard attribute for an interval, and something that a user may want to know.

Implementation is straight forward: self.right - self.left, which could be an argument against adding this, since it's something a user could easily do themselves. I think the explicit use of length would make code more readable. For example, consider the datetime safe path for Interval.mid, the midpoint of an Interval:

# datetime safe version
return self.left + 0.5 * (self.right - self.left)

This could be rewritten in a more explicit and clear manner with Interval.length:

 # datetime safe version 
 return self.left + 0.5 * self.length

Note that I don't think this can be implemented as __len__ for Interval, as I believe __len__ is required to return an integer, and intervals do not necessarily need to have integer length.

Expected Output

Scalar output for an Interval:

In [2]: iv = pd.Interval(1, 3)

In [3]: iv
Out[3]: Interval(1, 3, closed='right')

In [4]: iv.length
Out[4]: 2

An Index with entries denoting the length of each Interval for an IntervalIndex:

In [5]: idx = pd.IntervalIndex.from_breaks(pd.to_datetime(['20171010', '20171020', '20171111']))

In [6]: idx
IntervalIndex([(2017-10-10, 2017-10-20], (2017-10-20, 2017-11-11]]

In [7]: idx.length
Out[7]: TimedeltaIndex(['10 days', '22 days'], dtype='timedelta64[ns]', freq=None)

This comment has been minimized.


gfyoung commented Dec 15, 2017

Sounds reasonable to me. Go for it!

@gfyoung gfyoung closed this Dec 15, 2017


This comment has been minimized.


gfyoung commented Dec 15, 2017

I meant to hit "Comment" 😄

@gfyoung gfyoung reopened this Dec 15, 2017

@jreback jreback added this to the Next Major Release milestone Dec 15, 2017


This comment has been minimized.


jreback commented Dec 15, 2017


@jreback jreback modified the milestones: Next Major Release, 0.22.0 Dec 18, 2017

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment