Skip to content

CLN/DOC: Interval and IntervalIndex classes #18585

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

Merged
merged 1 commit into from
Dec 1, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
114 changes: 72 additions & 42 deletions pandas/_libs/interval.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -14,30 +14,46 @@ import numbers
_VALID_CLOSED = frozenset(['left', 'right', 'both', 'neither'])


cdef class IntervalMixin:
property closed_left:
def __get__(self):
return self.closed == 'left' or self.closed == 'both'

property closed_right:
def __get__(self):
return self.closed == 'right' or self.closed == 'both'

property open_left:
def __get__(self):
return not self.closed_left

property open_right:
def __get__(self):
return not self.closed_right

property mid:
def __get__(self):
try:
return 0.5 * (self.left + self.right)
except TypeError:
# datetime safe version
return self.left + 0.5 * (self.right - self.left)
cdef class IntervalMixin(object):

@property
def closed_left(self):
"""
Return True if the Interval is closed on the left-side, else False
"""
return self.closed in ('left', 'both')

@property
def closed_right(self):
"""
Return True if the Interval is closed on the right-side, else False
"""
return self.closed in ('right', 'both')

@property
def open_left(self):
"""
Return True if the Interval is open on the left-side, else False
"""
return not self.closed_left

@property
def open_right(self):
"""
Return True if the Interval is open on the right-side, else False
"""
return not self.closed_right

@property
def mid(self):
"""
Return the midpoint of the Interval
"""
try:
return 0.5 * (self.left + self.right)
except TypeError:
# datetime safe version
return self.left + 0.5 * (self.right - self.left)


cdef _interval_like(other):
Expand All @@ -55,12 +71,12 @@ cdef class Interval(IntervalMixin):
Parameters
----------
left : value
Left bound for interval.
Left bound for the interval
right : value
Right bound for interval.
closed : {'left', 'right', 'both', 'neither'}
Right bound for the interval
closed : {'left', 'right', 'both', 'neither'}, default 'right'
Whether the interval is closed on the left-side, right-side, both or
neither. Defaults to 'right'.
neither

Examples
--------
Expand All @@ -77,20 +93,30 @@ cdef class Interval(IntervalMixin):

See Also
--------
IntervalIndex : an Index of ``interval`` s that are all closed on the same
side.
cut, qcut : convert arrays of continuous data into categoricals/series of
``Interval``.
IntervalIndex : An Index of Interval objects that are all closed on the
same side.
cut, qcut : Convert arrays of continuous data into Categoricals/Series of
Interval.
"""

cdef readonly object left, right
cdef readonly object left
"""Left bound for the interval"""

cdef readonly object right
"""Right bound for the interval"""

cdef readonly str closed
"""
Whether the interval is closed on the left-side, right-side, both or
neither
"""

def __init__(self, left, right, str closed='right'):
# note: it is faster to just do these checks than to use a special
# constructor (__cinit__/__new__) to avoid them
if closed not in _VALID_CLOSED:
raise ValueError("invalid option for 'closed': %s" % closed)
msg = "invalid option for 'closed': {closed}".format(closed=closed)
raise ValueError(msg)
if not left <= right:
raise ValueError('left side of interval must be <= right side')
self.left = left
Expand Down Expand Up @@ -122,10 +148,11 @@ cdef class Interval(IntervalMixin):
if op == Py_EQ or op == Py_NE:
return NotImplemented
else:
name = type(self).__name__
other = type(other).__name__
op_str = {Py_LT: '<', Py_LE: '<=', Py_GT: '>', Py_GE: '>='}[op]
raise TypeError(
'unorderable types: %s() %s %s()' %
(type(self).__name__, op_str, type(other).__name__))
raise TypeError('unorderable types: {name}() {op} {other}()'
.format(name=name, op=op_str, other=other))

def __reduce__(self):
args = (self.left, self.right, self.closed)
Expand All @@ -145,15 +172,18 @@ cdef class Interval(IntervalMixin):
def __repr__(self):

left, right = self._repr_base()
return ('%s(%r, %r, closed=%r)' %
(type(self).__name__, left, right, self.closed))
name = type(self).__name__
repr_str = '{name}({left!r}, {right!r}, closed={closed!r})'.format(
name=name, left=left, right=right, closed=self.closed)
return repr_str

def __str__(self):

left, right = self._repr_base()
start_symbol = '[' if self.closed_left else '('
end_symbol = ']' if self.closed_right else ')'
return '%s%s, %s%s' % (start_symbol, left, right, end_symbol)
return '{start}{left}, {right}{end}'.format(
start=start_symbol, left=left, right=right, end=end_symbol)

def __add__(self, y):
if isinstance(y, numbers.Number):
Expand Down Expand Up @@ -222,8 +252,8 @@ cpdef intervals_to_interval_bounds(ndarray intervals):
continue

if not isinstance(interval, Interval):
raise TypeError("type {} with value {} is not an interval".format(
type(interval), interval))
raise TypeError("type {typ} with value {iv} is not an interval"
.format(typ=type(interval), iv=interval))

left[i] = interval.left
right[i] = interval.right
Expand Down
Loading