Skip to content
Merged
Show file tree
Hide file tree
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
10 changes: 8 additions & 2 deletions pandas/core/groupby/grouper.py
Original file line number Diff line number Diff line change
Expand Up @@ -491,8 +491,14 @@ def get_grouper(
raise ValueError("multiple levels only valid with MultiIndex")

if isinstance(level, str):
if obj.index.name != level:
raise ValueError(f"level name {level} is not the name of the index")
if axis == 0:
axis_name = "index"
else:
axis_name = "columns"
if getattr(obj, axis_name).name != level:
raise ValueError(
f"level name {level} is not the name of the {axis_name}"
)
elif level > 0 or level < -1:
raise ValueError("level > 0 or level < -1 only valid with MultiIndex")

Expand Down
12 changes: 12 additions & 0 deletions pandas/tests/groupby/test_grouping.py
Original file line number Diff line number Diff line change
Expand Up @@ -511,6 +511,18 @@ def test_groupby_level_index_names(self):
with pytest.raises(ValueError, match=msg):
df.groupby(level="foo")

def test_groupby_level_columns_names(self):
# This used to raise with 'level name exp is not the name of the index'
df = (
DataFrame({"exp": ["A"] * 3 + ["B"] * 3, "var1": range(6)})
.set_index("exp")
.T
)
df.groupby(level="exp", axis=1)
msg = "level name foo is not the name of the columns"
with pytest.raises(ValueError, match=msg):
df.groupby(level="foo", axis=1)

@pytest.mark.parametrize("sort", [True, False])
def test_groupby_level_with_nas(self, sort):
# GH 17537
Expand Down