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
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
25 changes: 25 additions & 0 deletions pandas/tests/generic/test_series.py
Original file line number Diff line number Diff line change
Expand Up @@ -151,3 +151,28 @@ def finalize(self, other, method=None, **kwargs):
# reset
Series._metadata = _metadata
Series.__finalize__ = _finalize # FIXME: use monkeypatch

# issue #43659
def test_rename_with_multiindex(self):
Copy link
Contributor

Choose a reason for hiding this comment

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

move here: pandas/tests/series/methods/test_rename.py

arrays = [
Copy link
Member

Choose a reason for hiding this comment

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

Please add reference in test not above

The test is to complicated. Please reduce number of rows and don't use something like list(zip(*arrays)). You can use MultiIndex.from_arrays

["bar", "bar", "baz", "baz", "foo", "foo", "qux", "qux"],
["one", "two", "one", "two", "one", "two", "one", "two"],
]

tuples = list(zip(*arrays))
index = MultiIndex.from_tuples(tuples, names=["first", "second"])
s = Series(np.ones(8), index=index)
result = s.rename(index={"one": "yes"}, level="second", errors="raise")

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

tuples_expected = list(zip(*arrays_expected))
index_expected = MultiIndex.from_tuples(
tuples_expected, names=["first", "second"]
)
series_expected = Series(np.ones(8), index=index_expected)

assert result.equals(series_expected)