Skip to content

Commit 4556c63

Browse files
committed
fix setting of index
1 parent a7ecced commit 4556c63

File tree

3 files changed

+14
-2
lines changed

3 files changed

+14
-2
lines changed

doc/source/whatsnew/v1.0.2.rst

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ Fixed regressions
1919
- Fixed regression in :meth:`Series.align` when ``other`` is a DataFrame and ``method`` is not None (:issue:`31785`)
2020
- Fixed regression in :meth:`pandas.core.groupby.RollingGroupby.apply` where the ``raw`` parameter was ignored (:issue:`31754`)
2121
- Fixed regression in :meth:`rolling(..).corr() <pandas.core.window.Rolling.corr>` when using a time offset (:issue:`31789`)
22-
-
22+
- Fixed regression in :meth:`Groupby.aggregate` which was failing on frames with MultiIndex columns and a custom function (:issue:`31777`)
2323

2424
.. ---------------------------------------------------------------------------
2525

pandas/core/groupby/generic.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -968,7 +968,8 @@ def aggregate(self, func=None, *args, **kwargs):
968968
result = self._aggregate_frame(func)
969969
else:
970970
result.columns = Index(
971-
result.columns.levels[0], name=self._selected_obj.columns.name
971+
[i[:-1] if len(i) > 2 else i[0] for i in result.columns],
972+
name=self._selected_obj.columns.name,
972973
)
973974

974975
if not self.as_index:

pandas/tests/groupby/aggregate/test_aggregate.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -679,6 +679,17 @@ def test_agg_relabel_multiindex_duplicates():
679679
tm.assert_frame_equal(result, expected)
680680

681681

682+
def test_multiindex_custom_func():
683+
# GH 31777
684+
df = pd.DataFrame(
685+
np.random.rand(10, 4), columns=pd.MultiIndex.from_product([[1, 2], [3, 4]])
686+
)
687+
grp = df.groupby(np.r_[np.ones(5), np.zeros(5)])
688+
result = grp.agg(lambda s: s.mean())
689+
expected = grp.agg("mean")
690+
tm.assert_frame_equal(result, expected)
691+
692+
682693
def myfunc(s):
683694
return np.percentile(s, q=0.90)
684695

0 commit comments

Comments
 (0)