Skip to content

Commit

Permalink
Groupby crash on a single level (pandas-dev#30229)
Browse files Browse the repository at this point in the history
  • Loading branch information
Ynob2000 authored and proost committed Dec 19, 2019
1 parent 3311ee3 commit a275552
Show file tree
Hide file tree
Showing 3 changed files with 12 additions and 7 deletions.
2 changes: 1 addition & 1 deletion doc/source/whatsnew/v1.0.0.rst
100644 → 100755
Original file line number Diff line number Diff line change
Expand Up @@ -824,7 +824,7 @@ Groupby/resample/rolling
- Bug in :meth:`DataFrameGroupBy.rolling().quantile()` ignoring ``interpolation`` keyword argument (:issue:`28779`)
- Bug in :meth:`DataFrame.groupby` where ``any``, ``all``, ``nunique`` and transform functions would incorrectly handle duplicate column labels (:issue:`21668`)
- Bug in :meth:`DataFrameGroupBy.agg` with timezone-aware datetime64 column incorrectly casting results to the original dtype (:issue:`29641`)
-
- Bug in :meth:`DataFrame.groupby` when using axis=1 and having a single level columns index (:issue:`30208`)

Reshaping
^^^^^^^^^
Expand Down
7 changes: 5 additions & 2 deletions pandas/core/groupby/grouper.py
Original file line number Diff line number Diff line change
Expand Up @@ -491,8 +491,11 @@ 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 obj._get_axis(axis).name != level:
raise ValueError(
f"level name {level} is not the name "
f"of the {obj._get_axis_name(axis)}"
)
elif level > 0 or level < -1:
raise ValueError("level > 0 or level < -1 only valid with MultiIndex")

Expand Down
10 changes: 6 additions & 4 deletions pandas/tests/groupby/test_grouping.py
Original file line number Diff line number Diff line change
Expand Up @@ -501,15 +501,17 @@ def test_groupby_level(self, sort, mframe, df):
with pytest.raises(ValueError, match=msg):
df.groupby(level=1)

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

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

0 comments on commit a275552

Please sign in to comment.