Skip to content

Commit e6ea00c

Browse files
Mofefjreback
authored andcommitted
BUG: incorrect set_labels in MI (pandas-dev#19058)
1 parent 2f6c1b1 commit e6ea00c

File tree

3 files changed

+19
-2
lines changed

3 files changed

+19
-2
lines changed

doc/source/whatsnew/v0.23.0.txt

+1
Original file line numberDiff line numberDiff line change
@@ -364,6 +364,7 @@ Indexing
364364
- Bug in indexing non-scalar value from ``Series`` having non-unique ``Index`` will return value flattened (:issue:`17610`)
365365
- Bug in :func:`DatetimeIndex.insert` where inserting ``NaT`` into a timezone-aware index incorrectly raised (:issue:`16357`)
366366
- Bug in ``__setitem__`` when indexing a :class:`DataFrame` with a 2-d boolean ndarray (:issue:`18582`)
367+
- Bug in :func:`MultiIndex.set_labels` which would cause casting (and potentially clipping) of the new labels if the ``level`` argument is not 0 or a list like [0, 1, ... ] (:issue:`19057`)
367368
- Bug in ``str.extractall`` when there were no matches empty :class:`Index` was returned instead of appropriate :class:`MultiIndex` (:issue:`19034`)
368369

369370
I/O

pandas/core/indexes/multi.py

+3-2
Original file line numberDiff line numberDiff line change
@@ -328,8 +328,9 @@ def _set_labels(self, labels, level=None, copy=False, validate=True,
328328
else:
329329
level = [self._get_level_number(l) for l in level]
330330
new_labels = list(self._labels)
331-
for l, lev, lab in zip(level, self.levels, labels):
332-
new_labels[l] = _ensure_frozen(
331+
for lev_idx, lab in zip(level, labels):
332+
lev = self.levels[lev_idx]
333+
new_labels[lev_idx] = _ensure_frozen(
333334
lab, lev, copy=copy)._shallow_copy()
334335
new_labels = FrozenList(new_labels)
335336

pandas/tests/indexes/test_multi.py

+15
Original file line numberDiff line numberDiff line change
@@ -327,6 +327,21 @@ def assert_matching(actual, expected):
327327
assert_matching(ind2.labels, new_labels)
328328
assert_matching(self.index.labels, labels)
329329

330+
# label changing for levels of different magnitude of categories
331+
ind = pd.MultiIndex.from_tuples([(0, i) for i in range(130)])
332+
new_labels = range(129, -1, -1)
333+
expected = pd.MultiIndex.from_tuples(
334+
[(0, i) for i in new_labels])
335+
336+
# [w/o mutation]
337+
result = ind.set_labels(labels=new_labels, level=1)
338+
assert result.equals(expected)
339+
340+
# [w/ mutation]
341+
result = ind.copy()
342+
result.set_labels(labels=new_labels, level=1, inplace=True)
343+
assert result.equals(expected)
344+
330345
def test_set_levels_labels_names_bad_input(self):
331346
levels, labels = self.index.levels, self.index.labels
332347
names = self.index.names

0 commit comments

Comments
 (0)