Skip to content

BUG: rename fails when using level #43667

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 12 commits into from
Sep 27, 2021
Merged
Show file tree
Hide file tree
Changes from 11 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions doc/source/whatsnew/v1.4.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -413,6 +413,7 @@ Interval

Indexing
^^^^^^^^
- Bug in :meth:`Series.rename` when index in Series is MultiIndex and level in rename is provided. (:issue:`43659`)
- 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`)
- 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`)
- Bug in :meth:`Series.loc` when with a :class:`MultiIndex` whose first level contains only ``np.nan`` values (:issue:`42055`)
Expand Down
6 changes: 5 additions & 1 deletion pandas/core/generic.py
Original file line number Diff line number Diff line change
Expand Up @@ -1147,7 +1147,11 @@ def rename(

# GH 13473
if not callable(replacements):
indexer = ax.get_indexer_for(replacements)
if ax._is_multi and level is not None:
indexer = ax.get_level_values(level).get_indexer_for(replacements)
else:
indexer = ax.get_indexer_for(replacements)

if errors == "raise" and len(indexer[indexer == -1]):
missing_labels = [
label
Expand Down
24 changes: 24 additions & 0 deletions pandas/tests/series/methods/test_rename.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

from pandas import (
Index,
MultiIndex,
Series,
)
import pandas._testing as tm
Expand Down Expand Up @@ -101,3 +102,26 @@ def test_rename_callable(self):
tm.assert_series_equal(result, expected)

assert result.name == expected.name

def test_rename_series_with_multiindex(self):
# issue #43659
arrays = [
["bar", "baz", "baz", "foo", "qux"],
["one", "one", "two", "two", "one"],
]

index = MultiIndex.from_arrays(arrays, names=["first", "second"])
s = Series(np.ones(5), index=index)
result = s.rename(index={"one": "yes"}, level="second", errors="raise")

arrays_expected = [
["bar", "baz", "baz", "foo", "qux"],
["yes", "yes", "two", "two", "yes"],
]

index_expected = MultiIndex.from_arrays(
arrays_expected, names=["first", "second"]
)
series_expected = Series(np.ones(5), index=index_expected)

assert result.equals(series_expected)