Skip to content

ENH: Implement cummax and cummin in _accumulate() for ordered Categorical arrays #58360

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 18 commits into from
Apr 23, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
18 commits
Select commit Hold shift + click to select a range
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
1 change: 1 addition & 0 deletions doc/source/whatsnew/v3.0.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ Other enhancements
- :class:`.errors.DtypeWarning` improved to include column names when mixed data types are detected (:issue:`58174`)
- :meth:`DataFrame.cummin`, :meth:`DataFrame.cummax`, :meth:`DataFrame.cumprod` and :meth:`DataFrame.cumsum` methods now have a ``numeric_only`` parameter (:issue:`53072`)
- :meth:`DataFrame.fillna` and :meth:`Series.fillna` can now accept ``value=None``; for non-object dtype the corresponding NA value will be used (:issue:`57723`)
- :meth:`Series.cummin` and :meth:`Series.cummax` now supports :class:`CategoricalDtype` (:issue:`52335`)

.. ---------------------------------------------------------------------------
.. _whatsnew_300.notable_bug_fixes:
Expand Down
23 changes: 23 additions & 0 deletions pandas/core/arrays/categorical.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
from shutil import get_terminal_size
from typing import (
TYPE_CHECKING,
Callable,
Literal,
cast,
overload,
Expand Down Expand Up @@ -2508,6 +2509,28 @@ def equals(self, other: object) -> bool:
return np.array_equal(self._codes, other._codes)
return False

def _accumulate(self, name: str, skipna: bool = True, **kwargs) -> Self:
func: Callable
if name == "cummin":
func = np.minimum.accumulate
elif name == "cummax":
func = np.maximum.accumulate
else:
raise TypeError(f"Accumulation {name} not supported for {type(self)}")
self.check_for_ordered(name)

codes = self.codes.copy()
mask = self.isna()
if func == np.minimum.accumulate:
codes[mask] = np.iinfo(codes.dtype.type).max
# no need to change codes for maximum because codes[mask] is already -1
if not skipna:
mask = np.maximum.accumulate(mask)

codes = func(codes)
codes[mask] = -1
return self._simple_new(codes, dtype=self._dtype)

@classmethod
def _concat_same_type(cls, to_concat: Sequence[Self], axis: AxisInt = 0) -> Self:
from pandas.core.dtypes.concat import union_categoricals
Expand Down
52 changes: 52 additions & 0 deletions pandas/tests/series/test_cumulative.py
Original file line number Diff line number Diff line change
Expand Up @@ -170,6 +170,58 @@ def test_cummethods_bool_in_object_dtype(self, method, expected):
result = getattr(ser, method)()
tm.assert_series_equal(result, expected)

@pytest.mark.parametrize(
"method, order",
[
["cummax", "abc"],
["cummin", "cba"],
],
)
def test_cummax_cummin_on_ordered_categorical(self, method, order):
# GH#52335
cat = pd.CategoricalDtype(list(order), ordered=True)
ser = pd.Series(
list("ababcab"),
dtype=cat,
)
result = getattr(ser, method)()
expected = pd.Series(
list("abbbccc"),
dtype=cat,
)
tm.assert_series_equal(result, expected)

@pytest.mark.parametrize(
"skip, exp",
[
[True, ["a", np.nan, "b", "b", "c"]],
[False, ["a", np.nan, np.nan, np.nan, np.nan]],
],
)
@pytest.mark.parametrize(
"method, order",
[
["cummax", "abc"],
["cummin", "cba"],
],
)
def test_cummax_cummin_ordered_categorical_nan(self, skip, exp, method, order):
# GH#52335
cat = pd.CategoricalDtype(list(order), ordered=True)
ser = pd.Series(
["a", np.nan, "b", "a", "c"],
dtype=cat,
)
result = getattr(ser, method)(skipna=skip)
expected = pd.Series(
exp,
dtype=cat,
)
tm.assert_series_equal(
result,
expected,
)

def test_cumprod_timedelta(self):
# GH#48111
ser = pd.Series([pd.Timedelta(days=1), pd.Timedelta(days=3)])
Expand Down
Loading