Skip to content

Commit c4ea34e

Browse files
committed
fix setting of index
1 parent a7ecced commit c4ea34e

File tree

3 files changed

+14
-3
lines changed

3 files changed

+14
-3
lines changed

doc/source/whatsnew/v1.0.2.rst

+1-1
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

+2-2
Original file line numberDiff line numberDiff line change
@@ -945,7 +945,6 @@ def aggregate(self, func=None, *args, **kwargs):
945945
return result
946946

947947
if result is None:
948-
949948
# grouper specific aggregations
950949
if self.grouper.nkeys > 1:
951950
return self._python_agg_general(func, *args, **kwargs)
@@ -968,7 +967,8 @@ def aggregate(self, func=None, *args, **kwargs):
968967
result = self._aggregate_frame(func)
969968
else:
970969
result.columns = Index(
971-
result.columns.levels[0], name=self._selected_obj.columns.name
970+
[i[:-1] if len(i) > 2 else i[0] for i in result.columns],
971+
name=self._selected_obj.columns.name,
972972
)
973973

974974
if not self.as_index:

pandas/tests/groupby/aggregate/test_aggregate.py

+11
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)