Skip to content

Fix groupby agg preserve subclass type #59680

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

Closed
Show file tree
Hide file tree
Changes from all commits
Commits
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
2 changes: 1 addition & 1 deletion doc/source/whatsnew/v2.3.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -142,7 +142,7 @@ Plotting

Groupby/resample/rolling
^^^^^^^^^^^^^^^^^^^^^^^^
-
- Bug in :meth:`DataFrame.groupby` followed by :meth:`DataFrameGroupBy.agg` not preserving subclass type of the original DataFrame (:issue:`59667`)
-

Reshaping
Expand Down
3 changes: 3 additions & 0 deletions pandas/core/groupby/generic.py
Original file line number Diff line number Diff line change
Expand Up @@ -1585,6 +1585,9 @@ def aggregate(self, func=None, *args, engine=None, engine_kwargs=None, **kwargs)
result = self._insert_inaxis_grouper(result)
result.index = default_index(len(result))

if isinstance(self.obj, type(self.obj)):
result = self.obj._constructor(result)

return result

agg = aggregate
Expand Down
30 changes: 30 additions & 0 deletions pandas/tests/groupby/test_groupby.py
Original file line number Diff line number Diff line change
Expand Up @@ -3005,6 +3005,36 @@ def test_groupby_agg_namedagg_with_duplicate_columns():
tm.assert_frame_equal(result, expected)


class MyDataFrame(DataFrame):
@property
def _constructor(self):
return MyDataFrame


@pytest.mark.parametrize(
"data, agg_dict, expected",
[
pytest.param(
{"A": [1, 1, 2, 2], "B": [1, 2, 3, 4]},
{"B": "sum"},
DataFrame({"B": [3, 7]}, index=Index([1, 2], name="A")),
),
pytest.param(
{"A": [1, 1, 2, 2], "B": [1, 2, 3, 4], "C": [4, 3, 2, 1]},
{"B": "sum", "C": "mean"},
DataFrame({"B": [3, 7], "C": [3.5, 1.5]}, index=Index([1, 2], name="A")),
),
],
)
def test_groupby_agg_preserves_subclass(data, agg_dict, expected):
# GH#59667
df = MyDataFrame(data)
result = df.groupby("A").agg(agg_dict)

assert isinstance(result, MyDataFrame)
tm.assert_frame_equal(result, expected)


def test_groupby_multi_index_codes():
# GH#54347
df = DataFrame(
Expand Down