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 12 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`)
- Implement :meth:`ExtensionArray._accumulate` operations ``cummax`` and ``cummin`` in :class:`Categorical` (:issue:`52335`)

.. ---------------------------------------------------------------------------
.. _whatsnew_300.notable_bug_fixes:
Expand Down
60 changes: 60 additions & 0 deletions pandas/core/array_algos/categorical_accumulations.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
"""
categorical_accumulations.py is for accumulation algorithms using a mask-based
approach for missing values.
"""

from __future__ import annotations

from typing import Callable

import numpy as np


def _cum_func(
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you just include all this logic in pandas/core/arrays/categorical.py

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I moved the logic into pandas/core/arrays/categorical.py

func: Callable,
values: np.ndarray,
*,
skipna: bool = True,
) -> np.ndarray:
"""
Accumulations for 1D categorical arrays.

We will modify values in place to replace NAs with the appropriate fill value.

Parameters
----------
func : np.maximum.accumulate, np.minimum.accumulate
values : np.ndarray
Numpy integer array with the values and with NAs being -1.
skipna : bool, default True
Whether to skip NA.
"""
dtype_info = np.iinfo(values.dtype.type)
try:
fill_value = {
np.maximum.accumulate: dtype_info.min,
np.minimum.accumulate: dtype_info.max,
}[func]
except KeyError as err:
raise NotImplementedError(
f"No accumulation for {func} implemented on BaseMaskedArray"
) from err

mask = values == -1
values[mask] = fill_value

if not skipna:
mask = np.maximum.accumulate(mask)

values = func(values)
values[mask] = -1

return values


def cummin(values: np.ndarray, *, skipna: bool = True) -> np.ndarray:
return _cum_func(np.minimum.accumulate, values, skipna=skipna)


def cummax(values: np.ndarray, *, skipna: bool = True) -> np.ndarray:
return _cum_func(np.maximum.accumulate, values, skipna=skipna)
14 changes: 14 additions & 0 deletions pandas/core/arrays/categorical.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,7 @@
factorize,
take_nd,
)
from pandas.core.array_algos import categorical_accumulations
from pandas.core.arrays._mixins import (
NDArrayBackedExtensionArray,
ravel_compat,
Expand Down Expand Up @@ -2508,6 +2509,19 @@ 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:
if name not in {"cummin", "cummax"}:
raise TypeError(f"Accumulation {name} not supported for {type(self)}")

self.check_for_ordered(name)

codes = self.codes.copy()

op = getattr(categorical_accumulations, name)
codes = op(codes, skipna=skipna, **kwargs)

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
49 changes: 49 additions & 0 deletions pandas/tests/arrays/categorical/test_cumulative.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
"""
Tests for Ordered Categorical Array cumulative operations.
"""

import numpy as np
import pytest

import pandas as pd
import pandas._testing as tm


class TestAccumulator:
@pytest.mark.parametrize(
"method, input, output",
[
["cummax", [1, 2, 1, 2, 3, 3, 2, 1], [1, 2, 2, 2, 3, 3, 3, 3]],
["cummin", [3, 2, 3, 2, 1, 1, 2, 3], [3, 2, 2, 2, 1, 1, 1, 1]],
],
)
def test_cummax_cummin_on_ordered_categorical(self, method, input, output):
# GH#52335
result = pd.Categorical(input, ordered=True)._accumulate(method)
tm.assert_extension_array_equal(result, pd.Categorical(output, ordered=True))

@pytest.mark.parametrize(
"method, skip, input, output",
[
["cummax", True, [1, np.nan, 2, 1, 3], [1, np.nan, 2, 2, 3]],
[
"cummax",
False,
[1, np.nan, 2, 1, 3],
[1, np.nan, np.nan, np.nan, np.nan],
],
["cummin", True, [3, np.nan, 2, 3, 1], [3, np.nan, 2, 2, 1]],
[
"cummin",
False,
[3, np.nan, 2, 3, 1],
[3, np.nan, np.nan, np.nan, np.nan],
],
],
)
def test_cummax_cummin_ordered_categorical_nan(self, skip, method, input, output):
# GH#52335
result = pd.Categorical(input, ordered=True)._accumulate(method, skipna=skip)
tm.assert_extension_array_equal(
result, pd.Categorical(output, categories=[1, 2, 3], ordered=True)
)
47 changes: 47 additions & 0 deletions pandas/tests/series/test_cumulative.py
Original file line number Diff line number Diff line change
Expand Up @@ -170,6 +170,53 @@ 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=pd.CategoricalDtype(list(order), ordered=True)
)
result = getattr(ser, method)()
tm.assert_series_equal(result, pd.Series(list("abbbccc"), dtype=cat))

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

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could you use pytest.mark.parametrize with skipna=True|False and the expected result?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added a pytest.mark.parametrize to test_cummax_cummin_ordered_categorical_nan with skipna and expected data

tm.assert_series_equal(
result,
pd.Series(
["a", np.nan, "b", "b", "c"],
dtype=pd.CategoricalDtype(list(order), ordered=True),
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you assign this to an expected variable?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Assigned all expected series to expected variables

),
)

result = getattr(ser, method)(skipna=False)
tm.assert_series_equal(
result,
pd.Series(
["a", np.nan, np.nan, np.nan, np.nan],
dtype=pd.CategoricalDtype(list(order), ordered=True),
),
)

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