From 7ea7ce79fd17b902290477b0c7163282c60ae4d5 Mon Sep 17 00:00:00 2001 From: Richard Shadrach Date: Sat, 22 Apr 2023 10:35:41 -0400 Subject: [PATCH 1/2] REGR: SeriesGroupBy.agg with list and categorical fails --- pandas/core/groupby/generic.py | 4 +- pandas/tests/groupby/test_categorical.py | 47 ++++++++++++++++++++++++ 2 files changed, 48 insertions(+), 3 deletions(-) diff --git a/pandas/core/groupby/generic.py b/pandas/core/groupby/generic.py index 2b68c002fe49f..d26448dffc11a 100644 --- a/pandas/core/groupby/generic.py +++ b/pandas/core/groupby/generic.py @@ -245,8 +245,7 @@ def aggregate(self, func=None, *args, engine=None, engine_kwargs=None, **kwargs) assert columns is not None # for mypy ret.columns = columns if not self.as_index: - ret = self._insert_inaxis_grouper(ret) - ret.index = default_index(len(ret)) + ret = ret.reset_index() return ret else: @@ -352,7 +351,6 @@ def _aggregate_multiple_funcs(self, arg, *args, **kwargs) -> DataFrame: output = self.obj._constructor_expanddim(indexed_output, index=None) output.columns = Index(key.label for key in results) - output = self._reindex_output(output) return output def _wrap_applied_output( diff --git a/pandas/tests/groupby/test_categorical.py b/pandas/tests/groupby/test_categorical.py index abce7dcfef444..c73b9db30b2db 100644 --- a/pandas/tests/groupby/test_categorical.py +++ b/pandas/tests/groupby/test_categorical.py @@ -14,6 +14,7 @@ qcut, ) import pandas._testing as tm +from pandas.api.typing import SeriesGroupBy from pandas.tests.groupby import get_groupby_method_args @@ -2036,3 +2037,49 @@ def test_groupby_default_depr(cat_columns, keys): klass = FutureWarning if set(cat_columns) & set(keys) else None with tm.assert_produces_warning(klass, match=msg): df.groupby(keys) + + +@pytest.mark.parametrize("test_series", [True, False]) +@pytest.mark.parametrize("keys", [["a1"], ["a1", "a2"]]) +def test_agg_list(request, as_index, observed, reduction_func, test_series, keys): + if test_series and reduction_func == "corrwith": + assert not hasattr(SeriesGroupBy, "corrwith") + pytest.skip("corrwith not implemented for SeriesGroupBy") + elif reduction_func == "corrwith": + msg = "DataFrameGroupBy.agg(['corrwith']) attempts to call SeriesGroupBy" + request.node.add_marker(pytest.mark.xfail(reason=msg)) + elif ( + not test_series + and reduction_func == "nunique" + and len(keys) != 1 + and not observed + and not as_index + ): + msg = "DataFrameGroupBy.nunique fails on categoricals" + request.node.add_marker(pytest.mark.xfail(reason=msg)) + + df = DataFrame({"a1": [0, 0, 1], "a2": [2, 3, 3], "b": [4, 5, 6]}) + df = df.astype({"a1": "category", "a2": "category"}) + if "a2" not in keys: + df = df.drop(columns="a2") + gb = df.groupby(by=keys, as_index=as_index, observed=observed) + if test_series: + gb = gb["b"] + args = get_groupby_method_args(reduction_func, df) + + result = gb.agg([reduction_func], *args) + expected = getattr(gb, reduction_func)(*args) + + if as_index and (test_series or reduction_func == "size"): + expected = expected.to_frame(reduction_func) + if not test_series: + if not as_index: + # TODO: Doesn't respect reset_index? + expected = expected.set_index(keys) + expected.columns = MultiIndex( + levels=[["b"], [reduction_func]], codes=[[0], [0]] + ) + elif not as_index: + expected.columns = keys + [reduction_func] + + tm.assert_equal(result, expected) From f63ac08f97a39002c35f60f71b32b428e3e5d170 Mon Sep 17 00:00:00 2001 From: Richard Shadrach Date: Sat, 22 Apr 2023 11:14:56 -0400 Subject: [PATCH 2/2] finish up --- doc/source/whatsnew/v2.0.1.rst | 1 + pandas/tests/groupby/test_categorical.py | 11 ++++++----- 2 files changed, 7 insertions(+), 5 deletions(-) diff --git a/doc/source/whatsnew/v2.0.1.rst b/doc/source/whatsnew/v2.0.1.rst index d340b034b6c2c..7768900a0f82e 100644 --- a/doc/source/whatsnew/v2.0.1.rst +++ b/doc/source/whatsnew/v2.0.1.rst @@ -19,6 +19,7 @@ Fixed regressions - Fixed regression in :meth:`DataFrame.sort_values` not resetting index when :class:`DataFrame` is already sorted and ``ignore_index=True`` (:issue:`52553`) - Fixed regression in :meth:`MultiIndex.isin` raising ``TypeError`` for ``Generator`` (:issue:`52568`) - Fixed regression in :meth:`Series.describe` showing ``RuntimeWarning`` for extension dtype :class:`Series` with one element (:issue:`52515`) +- Fixed regression in :meth:`SeriesGroupBy.agg` failing when grouping with categorical data, multiple groupings, ``as_index=False``, and a list of aggregations (:issue:`52760`) .. --------------------------------------------------------------------------- .. _whatsnew_201.bug_fixes: diff --git a/pandas/tests/groupby/test_categorical.py b/pandas/tests/groupby/test_categorical.py index c73b9db30b2db..f651609484f39 100644 --- a/pandas/tests/groupby/test_categorical.py +++ b/pandas/tests/groupby/test_categorical.py @@ -2042,20 +2042,21 @@ def test_groupby_default_depr(cat_columns, keys): @pytest.mark.parametrize("test_series", [True, False]) @pytest.mark.parametrize("keys", [["a1"], ["a1", "a2"]]) def test_agg_list(request, as_index, observed, reduction_func, test_series, keys): + # GH#52760 if test_series and reduction_func == "corrwith": assert not hasattr(SeriesGroupBy, "corrwith") pytest.skip("corrwith not implemented for SeriesGroupBy") elif reduction_func == "corrwith": - msg = "DataFrameGroupBy.agg(['corrwith']) attempts to call SeriesGroupBy" + msg = "GH#32293: attempts to call SeriesGroupBy.corrwith" request.node.add_marker(pytest.mark.xfail(reason=msg)) elif ( - not test_series - and reduction_func == "nunique" + reduction_func == "nunique" + and not test_series and len(keys) != 1 and not observed and not as_index ): - msg = "DataFrameGroupBy.nunique fails on categoricals" + msg = "GH#52848 - raises a ValueError" request.node.add_marker(pytest.mark.xfail(reason=msg)) df = DataFrame({"a1": [0, 0, 1], "a2": [2, 3, 3], "b": [4, 5, 6]}) @@ -2074,7 +2075,7 @@ def test_agg_list(request, as_index, observed, reduction_func, test_series, keys expected = expected.to_frame(reduction_func) if not test_series: if not as_index: - # TODO: Doesn't respect reset_index? + # TODO: GH#52849 - as_index=False is not respected expected = expected.set_index(keys) expected.columns = MultiIndex( levels=[["b"], [reduction_func]], codes=[[0], [0]]