Skip to content

Commit 2360697

Browse files
KalyanGokhalejorisvandenbossche
authored andcommitted
BUG: Should not raise errors in .set_names for MultiIndex with nlevels == 1 (GH21149) (#21196)
(cherry picked from commit a5259cc)
1 parent 952c364 commit 2360697

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
@@ -78,6 +78,7 @@ Indexing
7878

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

8384
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
@@ -164,6 +164,22 @@ def test_set_name_methods(self):
164164
assert res is None
165165
assert ind.names == new_names2
166166

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

0 commit comments

Comments
 (0)