Skip to content
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
BUG: Fix unexpected sort behavior when single level groupby from Mult…
…iIndex
  • Loading branch information
Licht-T committed Sep 28, 2017
commit 0e7bdb39bd6fcc8f25e7fa34100787b78537b32c
23 changes: 21 additions & 2 deletions pandas/core/groupby.py
Original file line number Diff line number Diff line change
Expand Up @@ -2586,10 +2586,27 @@ def _get_grouper(obj, key=None, axis=0, level=None, sort=True,
"""
group_axis = obj._get_axis(axis)

# validate that the passed level is compatible with the passed
# validate that the passed single level is compatible with the passed
# axis of the object
if level is not None:
if not isinstance(group_axis, MultiIndex):
# TODO: These if-block and else-block are almost same.
# MultiIndex instance check is removable, but it seems that there are
# some processes only for non-MultiIndex in else-block,
# eg. `obj.index.name != level`. We have to consider carefully whether
# these are applicable for MultiIndex. Even if these are applicable,
# we need to check if it makes no side effect to subsequent processes
# on the outside of this condition.
# (GH 17621)
if isinstance(group_axis, MultiIndex):
if is_list_like(level) and len(level) == 1:
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

actually this condition I think you can pull out of the MultiIndex check here (as the else is the same condition)

Copy link
Contributor Author

@Licht-T Licht-T Sep 27, 2017

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@jreback I am aware of this, but it seems that there are some processes only for non-MultiIndex in else. We have to consider carefully whether these are applicable for MultiIndex.
https://github.com/pandas-dev/pandas/pull/17621/files/e4cdd0726e685b0216056ba224ed363bf1e836f9#diff-720d374f1a709d0075a1f0a02445cd65R2618

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

When these are applicable, we also have to check if there is no side effect to subsequent processes.

level = level[0]

if key is None and is_scalar(level):
# Get the level values from group_axis
key = group_axis.get_level_values(level)
level = None

else:
# allow level to be a length-one list-like object
# (e.g., level=[0])
# GH 13901
Expand All @@ -2611,6 +2628,8 @@ def _get_grouper(obj, key=None, axis=0, level=None, sort=True,
raise ValueError('level > 0 or level < -1 only valid with '
' MultiIndex')

# NOTE: `group_axis` and `group_axis.get_level_values(level)`
# are same in this section.
level = None
key = group_axis

Expand Down