Skip to content
3 changes: 2 additions & 1 deletion doc/source/whatsnew/v0.23.1.txt
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,8 @@ Indexing

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

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

just say nlevels == 1 (in double backticks)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks - done

-

I/O
^^^
Expand Down
3 changes: 2 additions & 1 deletion pandas/core/indexes/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -1384,7 +1384,8 @@ def set_names(self, names, level=None, inplace=False):
names=[u'baz', u'bar'])
"""

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

if level is not None and not is_list_like(level) and is_list_like(
Expand Down
12 changes: 12 additions & 0 deletions pandas/tests/indexes/test_multi.py
Original file line number Diff line number Diff line change
Expand Up @@ -165,6 +165,18 @@ def test_set_name_methods(self):
assert res is None
assert ind.names == new_names2

def test_multiindex_set_names(self):
# GH 21149
'''Ensure that .set_names for MultiIndex with
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

use triple-double quotes

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

done

nlevels == 1 does not raise any errors
'''
result = pd.MultiIndex.from_product([[0, 1]])
result.set_names('first', level=0, inplace=True)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

test both inplace=True and False with a parameterized test

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

done

expected = pd.MultiIndex(levels=[[0, 1]],
labels=[[0, 1]],
names=['first'])
tm.assert_index_equal(result, expected)

def test_set_levels_labels_directly(self):
# setting levels/labels directly raises AttributeError

Expand Down