pandas-dev/pandas · #72058

ENH: Series.interval accessor (GH#16401)

jbrockmendel · merged Nov 13, 20267 files · 291 + / 0 −
doc/source/reference/arrays.rst3 + / 0 −
@@ -407,6 +407,9 @@ A collection of intervals may be stored in an :class:`arrays.IntervalArray`.     IntervalDtype +If the :class:`Series` is of dtype :class:`IntervalDtype`, ``Series.interval`` can be used to+access the interval data. See :ref:`api.series.interval` for more.+  .. Those attributes and methods are included in the API because the docstrings .. of IntervalIndex and IntervalArray are shared. Including it here to make
doc/source/reference/series.rst30 + / 0 −
@@ -289,6 +289,7 @@ to specific data types.     Series.cat     Series.dt     Series.sparse+    Series.interval     DataFrame.sparse     Index.str @@ -300,6 +301,7 @@ Datetime, Timedelta, Period :ref:`dt <api.series.dt>` String                      :ref:`str <api.series.str>` Categorical                 :ref:`cat <api.series.cat>` Sparse                      :ref:`sparse <api.series.sparse>`+Interval                    :ref:`interval <api.series.interval>` PyArrow list                :ref:`list <api.series.list>` PyArrow struct              :ref:`struct <api.series.struct>` =========================== =================================@@ -538,6 +540,34 @@ Sparse-dtype specific methods and attributes are provided under the    Series.sparse.to_coo  +.. _api.series.interval:++Interval accessor+~~~~~~~~~~~~~~~~~++Interval-dtype specific methods and attributes are available under+the ``Series.interval`` accessor.++.. autosummary::+   :toctree: api/+   :template: autosummary/accessor_attribute.rst++   Series.interval.left+   Series.interval.right+   Series.interval.mid+   Series.interval.length+   Series.interval.is_empty+   Series.interval.closed++.. autosummary::+   :toctree: api/+   :template: autosummary/accessor_method.rst++   Series.interval.contains+   Series.interval.overlaps+   Series.interval.set_closed++ .. _api.series.list:  List accessor
doc/source/whatsnew/v3.2.0.rst1 + / 0 −
@@ -37,6 +37,7 @@ Other enhancements - :meth:`DataFrame.plot.area` and :meth:`Series.plot.area` now accept keyword arguments that only the lines or only the filled areas support, such as ``hatch``, ``edgecolor`` and ``marker``, instead of raising ``AttributeError``; ``hatch`` also accepts a list with one hatch per column (:issue:`12354`) - :meth:`DataFrame.to_csv` and other writers now accept an ``os.PathLike`` such as :class:`pathlib.Path` for the ``archive_name`` entry of a zip or tar ``compression`` dict (:issue:`31934`) - :meth:`DataFrame.to_json`, :meth:`Series.to_json` and :meth:`DataFrame.to_xml` now warn when a compression method is requested but no path is given, since the returned string is not compressed, and raise for an unrecognized ``compression`` as they do with a path (:issue:`32326`)+- New :attr:`Series.interval` accessor for interval-dtype data, with ``left``, ``right``, ``mid``, ``length``, ``contains``, ``overlaps`` and more (:issue:`16401`) - :meth:`Series.astype` and :func:`array` with ``dtype="boolean"`` now convert values the same way as ``astype(bool)`` instead of raising for values other than booleans, 0 and 1 (e.g. ``"False"`` becomes ``True``), with missing values becoming ``NA`` (:issue:`37614`, :issue:`40566`) - :meth:`DatetimeIndex.floor`, :meth:`DatetimeIndex.ceil`, :meth:`Series.dt.floor`, :meth:`Series.dt.ceil`, :meth:`Timestamp.floor`, and :meth:`Timestamp.ceil` now accept a single step of a date-anchored frequency such as ``"MS"``, ``"QE"``, ``"W-SUN"``, or ``"B"`` (:issue:`15303`) - :meth:`Series.groupby` now accepts ``as_index=False``, returning aggregation results as a :class:`DataFrame` with the group labels as columns (:issue:`36507`)
pandas/core/arrays/interval.py109 + / 0 −
@@ -69,6 +69,7 @@     ABCDatetimeIndex,     ABCIntervalIndex,     ABCPeriodIndex,+    ABCSeries, ) from pandas.core.dtypes.missing import (     is_valid_na_for_dtype,@@ -77,6 +78,10 @@ )  from pandas.core import ops+from pandas.core.accessor import (+    PandasDelegate,+    delegate_names,+) from pandas.core.algorithms import (     isin,     take,@@ -89,6 +94,10 @@ ) from pandas.core.arrays.datetimes import DatetimeArray from pandas.core.arrays.timedeltas import TimedeltaArray+from pandas.core.base import (+    NoNewAttributesMixin,+    PandasObject,+) import pandas.core.common as com from pandas.core.construction import (     array as pd_array,@@ -113,6 +122,7 @@      from pandas import (         Index,+        Series,     )  @@ -2003,3 +2013,102 @@ def _maybe_convert_platform_interval(values) -> ArrayLike:         if values.dtype.kind in "iu" and values.dtype != np.int64:             values = values.astype(np.int64)     return values+++# ---------------------------------------------------------------------+# The Series.interval accessor+++@delegate_names(+    delegate=IntervalArray,+    accessors=["left", "right", "mid", "length", "is_empty", "closed"],+    typ="property",+)+@delegate_names(+    delegate=IntervalArray,+    accessors=["overlaps", "contains", "set_closed"],+    typ="method",+)+class IntervalAccessor(PandasDelegate, PandasObject, NoNewAttributesMixin):+    """+    Accessor object for interval properties of the Series values.++    Provides the endpoints, midpoints and lengths of the intervals, and+    elementwise checks for containment and overlap, each returned as a+    Series aligned with the original. A categorical Series with interval+    categories, such as the result of :func:`cut`, is also supported.++    Parameters+    ----------+    data : Series+        The Series with interval or interval-categorical dtype to which the+        accessor is attached.++    See Also+    --------+    arrays.IntervalArray : Pandas array for interval data.+    Series.cat : Accessor object for categorical properties of the Series values.+    Series.dt : Accessor object for datetimelike properties of the Series values.++    Examples+    --------+    >>> ser = pd.Series(pd.arrays.IntervalArray.from_breaks([0, 1, 3, 6]))+    >>> ser.interval.mid+    0    0.5+    1    2.0+    2    4.5+    dtype: float64++    >>> ser.interval.contains(2)+    0    False+    1     True+    2    False+    dtype: bool+    """++    def __init__(self, data) -> None:+        values = data.array+        if isinstance(values.dtype, CategoricalDtype) and isinstance(+            values.categories.dtype, IntervalDtype+        ):+            # take, not astype, so missing values upcast an integer subtype+            values = values.categories._values.take(values.codes, allow_fill=True)+        if not isinstance(values.dtype, IntervalDtype):+            raise AttributeError(+                "Can only use .interval accessor with an 'interval' dtype"+            )+        self._parent = data+        self._values = values+        self._freeze()++    def _wrap_result(self, result, copy: bool) -> Series:+        from pandas import Series++        return Series(+            extract_array(result),+            index=self._parent.index,+            name=self._parent.name,+            copy=copy,+        ).__finalize__(self._parent)++    def _delegate_property_get(self, name: str):+        result = getattr(self._values, name)+        if name == "closed":+            return result+        # left and right are views on the parent's data+        return self._wrap_result(result, copy=name in ("left", "right"))++    def _unbox(self, obj):+        # match Series comparison ops instead of silently matching by position+        if isinstance(obj, ABCSeries):+            if not obj.index.equals(self._parent.index):+                raise ValueError("Can only compare identically-labeled Series objects")+            return obj._values+        return obj++    def _delegate_method(self, name: str, *args, **kwargs) -> Series:+        args = tuple(self._unbox(arg) for arg in args)+        kwargs = {key: self._unbox(val) for key, val in kwargs.items()}+        method = getattr(self._values, name)+        # set_closed shares the parent's endpoint arrays+        return self._wrap_result(method(*args, **kwargs), copy=name == "set_closed")
pandas/core/series.py4 + / 0 −
@@ -120,6 +120,7 @@     StructAccessor, ) from pandas.core.arrays.categorical import CategoricalAccessor+from pandas.core.arrays.interval import IntervalAccessor from pandas.core.arrays.sparse import SparseAccessor from pandas.core.construction import (     array as pd_array,@@ -7417,6 +7418,9 @@ def to_period(     cat = Accessor("cat", CategoricalAccessor)     plot = Accessor("plot", pandas.plotting.PlotAccessor)     sparse = Accessor("sparse", SparseAccessor)+    # not in _accessors, so a label "interval" on a non-interval Series stays+    #  reachable as an attribute+    interval = Accessor("interval", IntervalAccessor)     struct = Accessor("struct", StructAccessor)     list = Accessor("list", ListAccessor) 
pandas/tests/generic/test_finalize.py16 + / 0 −
@@ -622,6 +622,22 @@ def test_categorical_accessor(method):     assert result.attrs == {"a": 1}  +@pytest.mark.parametrize(+    "method",+    [+        operator.attrgetter("left"),+        operator.attrgetter("mid"),+        operator.methodcaller("contains", 1),+        operator.methodcaller("set_closed", "both"),+    ],+)+def test_interval_accessor(method):+    s = pd.Series(pd.arrays.IntervalArray.from_breaks([0, 1, 2]))+    s.attrs = {"a": 1}+    result = method(s.interval)+    assert result.attrs == {"a": 1}++ # ---------------------------------------------------------------------------- # Groupby 
pandas/tests/series/accessors/test_interval_accessor.pyadded128 + / 0 −
@@ -0,0 +1,128 @@+import numpy as np+import pytest++import pandas as pd+import pandas._testing as tm+from pandas.core.arrays import IntervalArray+++@pytest.fixture(+    params=[+        [0, 1, 3, 6],+        [0.0, 1.5, 3.0, 4.5],+        pd.array([0, 1, 3, 6], dtype="Int64"),+        pd.date_range("2020-01-01", periods=4, tz="UTC"),+        pd.timedelta_range("1D", periods=4),+    ],+    ids=["int64", "float64", "Int64", "datetime64tz", "timedelta64"],+)+def ser(request):+    arr = IntervalArray.from_breaks(request.param)+    return pd.Series(arr, index=pd.Index(list("abc")), name="x")+++@pytest.mark.parametrize("attr", ["left", "right", "mid", "length", "is_empty"])+def test_interval_accessor_properties(ser, attr):+    # GH#16401+    result = getattr(ser.interval, attr)+    expected = pd.Series(+        pd.Index(getattr(ser.array, attr)), index=ser.index, name=ser.name+    )+    tm.assert_series_equal(result, expected)+++def test_interval_accessor_closed(ser):+    assert ser.interval.closed == "right"+    assert ser.interval.set_closed("both").interval.closed == "both"+++def test_interval_accessor_methods(ser):+    arr = ser.array+    for method, arg in [+        ("contains", arr.mid[1]),+        ("overlaps", arr[1]),+        ("set_closed", "left"),+    ]:+        result = getattr(ser.interval, method)(arg)+        expected = pd.Series(+            getattr(arr, method)(arg), index=ser.index, name=ser.name, copy=True+        )+        tm.assert_series_equal(result, expected)+    assert ser.interval.contains(arr.mid[1]).tolist() == [False, True, False]+++@pytest.mark.parametrize(+    "method", ["left", "right", "set_closed"], ids=["left", "right", "set_closed"]+)+def test_interval_accessor_result_does_not_share_data(ser, method):+    # mutating the result must not change the parent+    orig = ser.copy()+    if method == "set_closed":+        result = ser.interval.set_closed("both")+    else:+        result = getattr(ser.interval, method)+    result.iloc[0] = result.iloc[1]+    tm.assert_series_equal(ser, orig)+++def test_interval_accessor_contains_series():+    ser = pd.Series(IntervalArray.from_breaks([0, 1, 3, 6]), index=[10, 11, 12])+    other = pd.Series([0.5, 2, 9], index=ser.index)+    result = ser.interval.contains(other)+    tm.assert_series_equal(result, pd.Series([True, True, False], index=ser.index))++    # a misaligned Series is not matched by position+    msg = "Can only compare identically-labeled Series objects"+    with pytest.raises(ValueError, match=msg):+        ser.interval.contains(other.iloc[::-1])+    with pytest.raises(ValueError, match=msg):+        ser.interval.contains(other=other.iloc[::-1])+++def test_interval_accessor_missing():+    ser = pd.Series(IntervalArray([pd.Interval(0, 1), np.nan]))+    tm.assert_series_equal(ser.interval.left, pd.Series([0.0, np.nan]))+    tm.assert_series_equal(ser.interval.contains(0.5), pd.Series([True, False]))+    tm.assert_series_equal(+        ser.interval.overlaps(pd.Interval(0, 2)), pd.Series([True, False])+    )+++@pytest.mark.parametrize(+    "data",+    [+        pd.Series([1, 2]),+        pd.Series(["a", "b"], dtype="category"),+        pd.Series([1, 2], dtype="category"),+        pd.Series([pd.Interval(0, 1), pd.Interval(1, 2)], dtype=object),+    ],+)+def test_interval_accessor_invalid(data):+    msg = "Can only use .interval accessor with an 'interval' dtype"+    with pytest.raises(AttributeError, match=msg):+        data.interval+    assert not hasattr(data, "interval")+++def test_interval_accessor_categorical():+    # pd.cut returns a categorical with interval categories+    ser = pd.cut(pd.Series([0.5, 2, 4, np.nan], name="x"), [0, 1, 3, 6])+    dense = pd.Series(IntervalArray(ser), index=ser.index, name=ser.name)+    tm.assert_series_equal(ser.interval.mid, dense.interval.mid)+    tm.assert_series_equal(ser.interval.contains(2), dense.interval.contains(2))+    tm.assert_series_equal(+        ser.interval.set_closed("both"), dense.interval.set_closed("both")+    )+    assert ser.interval.mid.tolist()[:3] == [0.5, 2.0, 4.5]++    # without missing values the integer subtype is kept+    ser = pd.cut(pd.Series([0.5, 2]), [0, 1, 3])+    assert ser.interval.left.dtype == np.int64+++def test_interval_accessor_label_attribute_access():+    # a label named "interval" stays reachable on a non-interval Series+    row = pd.DataFrame({"interval": [5, 10], "n": [1, 2]}).iloc[0]+    assert row.interval == 5+    row = pd.DataFrame({"interval": [5, 10]}).astype("category").iloc[0]+    assert row.interval == 5