Skip to content

Commit d7a5b83

Browse files
authored
Fix GH-29442 DataFrame.groupby doesn't preserve _metadata (#35688)
1 parent 34afd03 commit d7a5b83

File tree

3 files changed

+21
-5
lines changed

3 files changed

+21
-5
lines changed

doc/source/whatsnew/v1.1.4.rst

+1-1
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ Fixed regressions
2727

2828
Bug fixes
2929
~~~~~~~~~
30-
-
30+
- Bug causing ``groupby(...).sum()`` and similar to not preserve metadata (:issue:`29442`)
3131

3232
.. ---------------------------------------------------------------------------
3333

pandas/core/groupby/groupby.py

+5-3
Original file line numberDiff line numberDiff line change
@@ -1004,8 +1004,9 @@ def _agg_general(
10041004
):
10051005
with group_selection_context(self):
10061006
# try a cython aggregation if we can
1007+
result = None
10071008
try:
1008-
return self._cython_agg_general(
1009+
result = self._cython_agg_general(
10091010
how=alias,
10101011
alt=npfunc,
10111012
numeric_only=numeric_only,
@@ -1024,8 +1025,9 @@ def _agg_general(
10241025
raise
10251026

10261027
# apply a non-cython aggregation
1027-
result = self.aggregate(lambda x: npfunc(x, axis=self.axis))
1028-
return result
1028+
if result is None:
1029+
result = self.aggregate(lambda x: npfunc(x, axis=self.axis))
1030+
return result.__finalize__(self.obj, method="groupby")
10291031

10301032
def _cython_agg_general(
10311033
self, how: str, alt=None, numeric_only: bool = True, min_count: int = -1

pandas/tests/generic/test_finalize.py

+15-1
Original file line numberDiff line numberDiff line change
@@ -762,13 +762,27 @@ def test_categorical_accessor(method):
762762
[
763763
operator.methodcaller("sum"),
764764
lambda x: x.agg("sum"),
765+
],
766+
)
767+
def test_groupby_finalize(obj, method):
768+
obj.attrs = {"a": 1}
769+
result = method(obj.groupby([0, 0]))
770+
assert result.attrs == {"a": 1}
771+
772+
773+
@pytest.mark.parametrize(
774+
"obj", [pd.Series([0, 0]), pd.DataFrame({"A": [0, 1], "B": [1, 2]})]
775+
)
776+
@pytest.mark.parametrize(
777+
"method",
778+
[
765779
lambda x: x.agg(["sum", "count"]),
766780
lambda x: x.transform(lambda y: y),
767781
lambda x: x.apply(lambda y: y),
768782
],
769783
)
770784
@not_implemented_mark
771-
def test_groupby(obj, method):
785+
def test_groupby_finalize_not_implemented(obj, method):
772786
obj.attrs = {"a": 1}
773787
result = method(obj.groupby([0, 0]))
774788
assert result.attrs == {"a": 1}

0 commit comments

Comments
 (0)