Skip to content

Commit a275552

Browse files
Ynob2000proost
authored andcommitted
Groupby crash on a single level (pandas-dev#30229)
1 parent 3311ee3 commit a275552

File tree

3 files changed

+12
-7
lines changed

3 files changed

+12
-7
lines changed

doc/source/whatsnew/v1.0.0.rst

100644100755
+1-1
Original file line numberDiff line numberDiff line change
@@ -824,7 +824,7 @@ Groupby/resample/rolling
824824
- Bug in :meth:`DataFrameGroupBy.rolling().quantile()` ignoring ``interpolation`` keyword argument (:issue:`28779`)
825825
- Bug in :meth:`DataFrame.groupby` where ``any``, ``all``, ``nunique`` and transform functions would incorrectly handle duplicate column labels (:issue:`21668`)
826826
- Bug in :meth:`DataFrameGroupBy.agg` with timezone-aware datetime64 column incorrectly casting results to the original dtype (:issue:`29641`)
827-
-
827+
- Bug in :meth:`DataFrame.groupby` when using axis=1 and having a single level columns index (:issue:`30208`)
828828

829829
Reshaping
830830
^^^^^^^^^

pandas/core/groupby/grouper.py

+5-2
Original file line numberDiff line numberDiff line change
@@ -491,8 +491,11 @@ def get_grouper(
491491
raise ValueError("multiple levels only valid with MultiIndex")
492492

493493
if isinstance(level, str):
494-
if obj.index.name != level:
495-
raise ValueError(f"level name {level} is not the name of the index")
494+
if obj._get_axis(axis).name != level:
495+
raise ValueError(
496+
f"level name {level} is not the name "
497+
f"of the {obj._get_axis_name(axis)}"
498+
)
496499
elif level > 0 or level < -1:
497500
raise ValueError("level > 0 or level < -1 only valid with MultiIndex")
498501

pandas/tests/groupby/test_grouping.py

+6-4
Original file line numberDiff line numberDiff line change
@@ -501,15 +501,17 @@ def test_groupby_level(self, sort, mframe, df):
501501
with pytest.raises(ValueError, match=msg):
502502
df.groupby(level=1)
503503

504-
def test_groupby_level_index_names(self):
504+
def test_groupby_level_index_names(self, axis):
505505
# GH4014 this used to raise ValueError since 'exp'>1 (in py2)
506506
df = DataFrame({"exp": ["A"] * 3 + ["B"] * 3, "var1": range(6)}).set_index(
507507
"exp"
508508
)
509-
df.groupby(level="exp")
510-
msg = "level name foo is not the name of the index"
509+
if axis in (1, "columns"):
510+
df = df.T
511+
df.groupby(level="exp", axis=axis)
512+
msg = f"level name foo is not the name of the {df._get_axis_name(axis)}"
511513
with pytest.raises(ValueError, match=msg):
512-
df.groupby(level="foo")
514+
df.groupby(level="foo", axis=axis)
513515

514516
@pytest.mark.parametrize("sort", [True, False])
515517
def test_groupby_level_with_nas(self, sort):

0 commit comments

Comments
 (0)