Skip to content

Commit 88d0fa3

Browse files
KalyanGokhaledavid-liu-brattle-1
authored andcommitted
BUG: Should not raise errors in .set_names for MultiIndex with nlevels == 1 (GH21149) (pandas-dev#21196)
1 parent 96a5aa6 commit 88d0fa3

File tree

3 files changed

+19
-1
lines changed

3 files changed

+19
-1
lines changed

doc/source/whatsnew/v0.23.1.txt

+1
Original file line numberDiff line numberDiff line change
@@ -80,6 +80,7 @@ Indexing
8080

8181
- Bug in :meth:`Series.reset_index` where appropriate error was not raised with an invalid level name (:issue:`20925`)
8282
- Bug in :func:`interval_range` when ``start``/``periods`` or ``end``/``periods`` are specified with float ``start`` or ``end`` (:issue:`21161`)
83+
- Bug in :meth:`MultiIndex.set_names` where error raised for a ``MultiIndex`` with ``nlevels == 1`` (:issue:`21149`)
8384
-
8485

8586
I/O

pandas/core/indexes/base.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -1384,7 +1384,8 @@ def set_names(self, names, level=None, inplace=False):
13841384
names=[u'baz', u'bar'])
13851385
"""
13861386

1387-
if level is not None and self.nlevels == 1:
1387+
from .multi import MultiIndex
1388+
if level is not None and not isinstance(self, MultiIndex):
13881389
raise ValueError('Level must be None for non-MultiIndex')
13891390

13901391
if level is not None and not is_list_like(level) and is_list_like(

pandas/tests/indexes/test_multi.py

+16
Original file line numberDiff line numberDiff line change
@@ -165,6 +165,22 @@ def test_set_name_methods(self):
165165
assert res is None
166166
assert ind.names == new_names2
167167

168+
@pytest.mark.parametrize('inplace', [True, False])
169+
def test_set_names_with_nlevel_1(self, inplace):
170+
# GH 21149
171+
# Ensure that .set_names for MultiIndex with
172+
# nlevels == 1 does not raise any errors
173+
expected = pd.MultiIndex(levels=[[0, 1]],
174+
labels=[[0, 1]],
175+
names=['first'])
176+
m = pd.MultiIndex.from_product([[0, 1]])
177+
result = m.set_names('first', level=0, inplace=inplace)
178+
179+
if inplace:
180+
result = m
181+
182+
tm.assert_index_equal(result, expected)
183+
168184
def test_set_levels_labels_directly(self):
169185
# setting levels/labels directly raises AttributeError
170186

0 commit comments

Comments
 (0)