Skip to content

Commit 0e7bdb3

Browse files
committed
BUG: Fix unexpected sort behavior when single level groupby from MultiIndex
1 parent 074b485 commit 0e7bdb3

File tree

1 file changed

+21
-2
lines changed

1 file changed

+21
-2
lines changed

pandas/core/groupby.py

Lines changed: 21 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2586,10 +2586,27 @@ def _get_grouper(obj, key=None, axis=0, level=None, sort=True,
25862586
"""
25872587
group_axis = obj._get_axis(axis)
25882588

2589-
# validate that the passed level is compatible with the passed
2589+
# validate that the passed single level is compatible with the passed
25902590
# axis of the object
25912591
if level is not None:
2592-
if not isinstance(group_axis, MultiIndex):
2592+
# TODO: These if-block and else-block are almost same.
2593+
# MultiIndex instance check is removable, but it seems that there are
2594+
# some processes only for non-MultiIndex in else-block,
2595+
# eg. `obj.index.name != level`. We have to consider carefully whether
2596+
# these are applicable for MultiIndex. Even if these are applicable,
2597+
# we need to check if it makes no side effect to subsequent processes
2598+
# on the outside of this condition.
2599+
# (GH 17621)
2600+
if isinstance(group_axis, MultiIndex):
2601+
if is_list_like(level) and len(level) == 1:
2602+
level = level[0]
2603+
2604+
if key is None and is_scalar(level):
2605+
# Get the level values from group_axis
2606+
key = group_axis.get_level_values(level)
2607+
level = None
2608+
2609+
else:
25932610
# allow level to be a length-one list-like object
25942611
# (e.g., level=[0])
25952612
# GH 13901
@@ -2611,6 +2628,8 @@ def _get_grouper(obj, key=None, axis=0, level=None, sort=True,
26112628
raise ValueError('level > 0 or level < -1 only valid with '
26122629
' MultiIndex')
26132630

2631+
# NOTE: `group_axis` and `group_axis.get_level_values(level)`
2632+
# are same in this section.
26142633
level = None
26152634
key = group_axis
26162635

0 commit comments

Comments
 (0)