Skip to content

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

Closed
@jschendel

Description

@jschendel

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
Out[6]:
IntervalIndex([(2017-10-10, 2017-10-20], (2017-10-20, 2017-11-11]]
              closed='right',
              dtype='interval[datetime64[ns]]')

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

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions