Skip to content

Commit e0fa388

Browse files
imankulovPingviinituutti
authored andcommitted
BUG: Let MultiIndex.set_levels accept any iterable (pandas-dev#23273) (pandas-dev#23291)
1 parent 652e42e commit e0fa388

File tree

3 files changed

+18
-0
lines changed

3 files changed

+18
-0
lines changed

doc/source/whatsnew/v0.24.0.txt

+1
Original file line numberDiff line numberDiff line change
@@ -1091,6 +1091,7 @@ Indexing
10911091
- Bug in :meth:`DataFrame.loc` when indexing with an :class:`IntervalIndex` (:issue:`19977`)
10921092
- :class:`Index` no longer mangles ``None``, ``NaN`` and ``NaT``, i.e. they are treated as three different keys. However, for numeric Index all three are still coerced to a ``NaN`` (:issue:`22332`)
10931093
- Bug in `scalar in Index` if scalar is a float while the ``Index`` is of integer dtype (:issue:`22085`)
1094+
- Bug in `MultiIndex.set_levels` when levels value is not subscriptable (:issue:`23273`)
10941095

10951096
Missing
10961097
^^^^^^^

pandas/core/indexes/multi.py

+3
Original file line numberDiff line numberDiff line change
@@ -389,6 +389,9 @@ def set_levels(self, levels, level=None, inplace=False,
389389
labels=[[0, 0, 1, 1], [0, 1, 0, 1]],
390390
names=[u'foo', u'bar'])
391391
"""
392+
if is_list_like(levels) and not isinstance(levels, Index):
393+
levels = list(levels)
394+
392395
if level is not None and not is_list_like(level):
393396
if not is_list_like(levels):
394397
raise TypeError("Levels must be list-like")

pandas/tests/indexes/multi/test_get_set.py

+14
Original file line numberDiff line numberDiff line change
@@ -414,3 +414,17 @@ def test_set_value_keeps_names():
414414
df.at[('grethe', '4'), 'one'] = 99.34
415415
assert df._is_copy is None
416416
assert df.index.names == ('Name', 'Number')
417+
418+
419+
def test_set_levels_with_iterable():
420+
# GH23273
421+
sizes = [1, 2, 3]
422+
colors = ['black'] * 3
423+
index = pd.MultiIndex.from_arrays([sizes, colors], names=['size', 'color'])
424+
425+
result = index.set_levels(map(int, ['3', '2', '1']), level='size')
426+
427+
expected_sizes = [3, 2, 1]
428+
expected = pd.MultiIndex.from_arrays([expected_sizes, colors],
429+
names=['size', 'color'])
430+
tm.assert_index_equal(result, expected)

0 commit comments

Comments
 (0)