Skip to content

Commit 6b77a05

Browse files
meeseeksmachineTomAugspurger
authored andcommitted
Backport PR #27814: BUG: Series.rename raises error on values accepted by Series construc… (#28087)
1 parent 91aa2f5 commit 6b77a05

File tree

3 files changed

+23
-5
lines changed

3 files changed

+23
-5
lines changed

doc/source/whatsnew/v0.25.1.rst

+1
Original file line numberDiff line numberDiff line change
@@ -108,6 +108,7 @@ Other
108108
^^^^^
109109

110110
- Bug in :meth:`Series.replace` and :meth:`DataFrame.replace` when replacing timezone-aware timestamps using a dict-like replacer (:issue:`27720`)
111+
- Bug in :meth:`Series.rename` when using a custom type indexer. Now any value that isn't callable or dict-like is treated as a scalar. (:issue:`27814`)
111112

112113
.. _whatsnew_0.251.contributors:
113114

pandas/core/series.py

+3-5
Original file line numberDiff line numberDiff line change
@@ -4207,12 +4207,10 @@ def rename(self, index=None, **kwargs):
42074207
"""
42084208
kwargs["inplace"] = validate_bool_kwarg(kwargs.get("inplace", False), "inplace")
42094209

4210-
non_mapping = is_scalar(index) or (
4211-
is_list_like(index) and not is_dict_like(index)
4212-
)
4213-
if non_mapping:
4210+
if callable(index) or is_dict_like(index):
4211+
return super().rename(index=index, **kwargs)
4212+
else:
42144213
return self._set_name(index, inplace=kwargs.get("inplace"))
4215-
return super().rename(index=index, **kwargs)
42164214

42174215
@Substitution(**_shared_doc_kwargs)
42184216
@Appender(generic.NDFrame.reindex.__doc__)

pandas/tests/series/test_alter_axes.py

+19
Original file line numberDiff line numberDiff line change
@@ -267,6 +267,25 @@ def test_rename_axis_none(self, kwargs):
267267
expected = Series([1, 2, 3], index=expected_index)
268268
tm.assert_series_equal(result, expected)
269269

270+
def test_rename_with_custom_indexer(self):
271+
# GH 27814
272+
class MyIndexer:
273+
pass
274+
275+
ix = MyIndexer()
276+
s = Series([1, 2, 3]).rename(ix)
277+
assert s.name is ix
278+
279+
def test_rename_with_custom_indexer_inplace(self):
280+
# GH 27814
281+
class MyIndexer:
282+
pass
283+
284+
ix = MyIndexer()
285+
s = Series([1, 2, 3])
286+
s.rename(ix, inplace=True)
287+
assert s.name is ix
288+
270289
def test_set_axis_inplace_axes(self, axis_series):
271290
# GH14636
272291
ser = Series(np.arange(4), index=[1, 3, 5, 7], dtype="int64")

0 commit comments

Comments
 (0)