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
fa74733
Added tests with and without np.nan
xiangchris Apr 14, 2024
269dcfb
Added tests for cummin and cummax
xiangchris Apr 16, 2024
a8a1f37
Merge branch 'accumulate_categorical' of github.com:bdwzhangumich/pan…
xiangchris Apr 16, 2024
9ec47bf
Fixed series tests expected series, rewrote categorical arrays to use…
xiangchris Apr 17, 2024
c224faf
Fixed cat not defined error and misspelling
xiangchris Apr 17, 2024
330b60d
Implement _accumulate for Categorical
bdwzhangumich Apr 17, 2024
e927cda
Merge branch 'pandas-dev:main' into accumulate_categorical
bdwzhangumich Apr 17, 2024
0122334
fixed misspellings in tests
xiangchris Apr 17, 2024
4caea9f
Merge branch 'accumulate_categorical' of github.com:bdwzhangumich/pan…
xiangchris Apr 17, 2024
098ad64
fixed expected categories on tests
xiangchris Apr 21, 2024
126bc19
Updated whatsnew
bdwzhangumich Apr 21, 2024
498ad6d
Merge branch 'pandas-dev:main' into accumulate_categorical
bdwzhangumich Apr 21, 2024
18a86e2
Update doc/source/whatsnew/v3.0.0.rst
bdwzhangumich Apr 22, 2024
5c5ac3c
Removed testing for _accumulate.
xiangchris Apr 22, 2024
7934f74
Merge branch 'accumulate_categorical' of github.com:bdwzhangumich/pan…
xiangchris Apr 22, 2024
1abad3e
Moved categorical_accumulations.py logic to categorical.py
bdwzhangumich Apr 22, 2024
6be5f8c
Merge branch 'main' into accumulate_categorical
xiangchris Apr 23, 2024
babc835
Assigned expected results to expected variable; Added pytest.mark.par…
xiangchris Apr 23, 2024
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