Skip to content

Commit 21c2991

Browse files
authored
BUG: rename fails when using level (#43667)
1 parent 7692d28 commit 21c2991

File tree

3 files changed

+30
-1
lines changed

3 files changed

+30
-1
lines changed

doc/source/whatsnew/v1.4.0.rst

+1
Original file line numberDiff line numberDiff line change
@@ -418,6 +418,7 @@ Interval
418418

419419
Indexing
420420
^^^^^^^^
421+
- Bug in :meth:`Series.rename` when index in Series is MultiIndex and level in rename is provided. (:issue:`43659`)
421422
- Bug in :meth:`DataFrame.truncate` and :meth:`Series.truncate` when the object's Index has a length greater than one but only one unique value (:issue:`42365`)
422423
- Bug in :meth:`Series.loc` and :meth:`DataFrame.loc` with a :class:`MultiIndex` when indexing with a tuple in which one of the levels is also a tuple (:issue:`27591`)
423424
- Bug in :meth:`Series.loc` when with a :class:`MultiIndex` whose first level contains only ``np.nan`` values (:issue:`42055`)

pandas/core/generic.py

+5-1
Original file line numberDiff line numberDiff line change
@@ -1145,7 +1145,11 @@ def rename(
11451145

11461146
# GH 13473
11471147
if not callable(replacements):
1148-
indexer = ax.get_indexer_for(replacements)
1148+
if ax._is_multi and level is not None:
1149+
indexer = ax.get_level_values(level).get_indexer_for(replacements)
1150+
else:
1151+
indexer = ax.get_indexer_for(replacements)
1152+
11491153
if errors == "raise" and len(indexer[indexer == -1]):
11501154
missing_labels = [
11511155
label

pandas/tests/series/methods/test_rename.py

+24
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44

55
from pandas import (
66
Index,
7+
MultiIndex,
78
Series,
89
)
910
import pandas._testing as tm
@@ -101,3 +102,26 @@ def test_rename_callable(self):
101102
tm.assert_series_equal(result, expected)
102103

103104
assert result.name == expected.name
105+
106+
def test_rename_series_with_multiindex(self):
107+
# issue #43659
108+
arrays = [
109+
["bar", "baz", "baz", "foo", "qux"],
110+
["one", "one", "two", "two", "one"],
111+
]
112+
113+
index = MultiIndex.from_arrays(arrays, names=["first", "second"])
114+
s = Series(np.ones(5), index=index)
115+
result = s.rename(index={"one": "yes"}, level="second", errors="raise")
116+
117+
arrays_expected = [
118+
["bar", "baz", "baz", "foo", "qux"],
119+
["yes", "yes", "two", "two", "yes"],
120+
]
121+
122+
index_expected = MultiIndex.from_arrays(
123+
arrays_expected, names=["first", "second"]
124+
)
125+
series_expected = Series(np.ones(5), index=index_expected)
126+
127+
tm.assert_series_equal(result, series_expected)

0 commit comments

Comments
 (0)