Skip to content

Commit c3ed803

Browse files
JapanuspusJulianWgs
authored andcommitted
Fix pandas-devGH-29442 DataFrame.groupby doesn't preserve _metadata (pandas-dev#35688)
1 parent 5e34e35 commit c3ed803

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
@@ -1010,8 +1010,9 @@ def _agg_general(
10101010
):
10111011
with group_selection_context(self):
10121012
# try a cython aggregation if we can
1013+
result = None
10131014
try:
1014-
return self._cython_agg_general(
1015+
result = self._cython_agg_general(
10151016
how=alias,
10161017
alt=npfunc,
10171018
numeric_only=numeric_only,
@@ -1030,8 +1031,9 @@ def _agg_general(
10301031
raise
10311032

10321033
# apply a non-cython aggregation
1033-
result = self.aggregate(lambda x: npfunc(x, axis=self.axis))
1034-
return result
1034+
if result is None:
1035+
result = self.aggregate(lambda x: npfunc(x, axis=self.axis))
1036+
return result.__finalize__(self.obj, method="groupby")
10351037

10361038
def _cython_agg_general(
10371039
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)