Skip to content

Commit 3af68dc

Browse files
phoflrhshadrach
andauthored
Backport PR #52850 on branch 2.0.x (REGR: SeriesGroupBy.agg with multiple categoricals, as_index=False, and a list fails) (#52854)
* REGR: SeriesGroupBy.agg with multiple categoricals, as_index=False, and a list fails (#52850) (cherry picked from commit 2ac0da4) * Fixup for 2.0.x --------- Co-authored-by: Richard Shadrach <45562402+rhshadrach@users.noreply.github.com>
1 parent d220466 commit 3af68dc

File tree

3 files changed

+50
-3
lines changed

3 files changed

+50
-3
lines changed

doc/source/whatsnew/v2.0.1.rst

+1
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ Fixed regressions
1919
- Fixed regression in :meth:`DataFrame.sort_values` not resetting index when :class:`DataFrame` is already sorted and ``ignore_index=True`` (:issue:`52553`)
2020
- Fixed regression in :meth:`MultiIndex.isin` raising ``TypeError`` for ``Generator`` (:issue:`52568`)
2121
- Fixed regression in :meth:`Series.describe` showing ``RuntimeWarning`` for extension dtype :class:`Series` with one element (:issue:`52515`)
22+
- Fixed regression in :meth:`SeriesGroupBy.agg` failing when grouping with categorical data, multiple groupings, ``as_index=False``, and a list of aggregations (:issue:`52760`)
2223

2324
.. ---------------------------------------------------------------------------
2425
.. _whatsnew_201.bug_fixes:

pandas/core/groupby/generic.py

+1-3
Original file line numberDiff line numberDiff line change
@@ -241,8 +241,7 @@ def aggregate(self, func=None, *args, engine=None, engine_kwargs=None, **kwargs)
241241
assert columns is not None # for mypy
242242
ret.columns = columns
243243
if not self.as_index:
244-
ret = self._insert_inaxis_grouper(ret)
245-
ret.index = default_index(len(ret))
244+
ret = ret.reset_index()
246245
return ret
247246

248247
else:
@@ -328,7 +327,6 @@ def _aggregate_multiple_funcs(self, arg, *args, **kwargs) -> DataFrame:
328327
output = self.obj._constructor_expanddim(indexed_output, index=None)
329328
output.columns = Index(key.label for key in results)
330329

331-
output = self._reindex_output(output)
332330
return output
333331

334332
def _wrap_applied_output(

pandas/tests/groupby/test_categorical.py

+48
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
qcut,
1515
)
1616
import pandas._testing as tm
17+
from pandas.core.groupby.generic import SeriesGroupBy
1718
from pandas.tests.groupby import get_groupby_method_args
1819

1920

@@ -2007,3 +2008,50 @@ def test_many_categories(as_index, sort, index_kind, ordered):
20072008
expected = DataFrame({"a": Series(index), "b": data})
20082009

20092010
tm.assert_frame_equal(result, expected)
2011+
2012+
2013+
@pytest.mark.parametrize("test_series", [True, False])
2014+
@pytest.mark.parametrize("keys", [["a1"], ["a1", "a2"]])
2015+
def test_agg_list(request, as_index, observed, reduction_func, test_series, keys):
2016+
# GH#52760
2017+
if test_series and reduction_func == "corrwith":
2018+
assert not hasattr(SeriesGroupBy, "corrwith")
2019+
pytest.skip("corrwith not implemented for SeriesGroupBy")
2020+
elif reduction_func == "corrwith":
2021+
msg = "GH#32293: attempts to call SeriesGroupBy.corrwith"
2022+
request.node.add_marker(pytest.mark.xfail(reason=msg))
2023+
elif (
2024+
reduction_func == "nunique"
2025+
and not test_series
2026+
and len(keys) != 1
2027+
and not observed
2028+
and not as_index
2029+
):
2030+
msg = "GH#52848 - raises a ValueError"
2031+
request.node.add_marker(pytest.mark.xfail(reason=msg))
2032+
2033+
df = DataFrame({"a1": [0, 0, 1], "a2": [2, 3, 3], "b": [4, 5, 6]})
2034+
df = df.astype({"a1": "category", "a2": "category"})
2035+
if "a2" not in keys:
2036+
df = df.drop(columns="a2")
2037+
gb = df.groupby(by=keys, as_index=as_index, observed=observed)
2038+
if test_series:
2039+
gb = gb["b"]
2040+
args = get_groupby_method_args(reduction_func, df)
2041+
2042+
result = gb.agg([reduction_func], *args)
2043+
expected = getattr(gb, reduction_func)(*args)
2044+
2045+
if as_index and (test_series or reduction_func == "size"):
2046+
expected = expected.to_frame(reduction_func)
2047+
if not test_series:
2048+
if not as_index:
2049+
# TODO: GH#52849 - as_index=False is not respected
2050+
expected = expected.set_index(keys)
2051+
expected.columns = MultiIndex(
2052+
levels=[["b"], [reduction_func]], codes=[[0], [0]]
2053+
)
2054+
elif not as_index:
2055+
expected.columns = keys + [reduction_func]
2056+
2057+
tm.assert_equal(result, expected)

0 commit comments

Comments
 (0)