Skip to content

Commit b551b28

Browse files
committed
PERF/API: Treat series as array-like for rename_categories
HEAD: ``` [ 50.00%] ··· Running categoricals.Categoricals3.time_rank_string_cat 6.63ms [ 50.00%] ····· [100.00%] ··· Running categoricals.Categoricals3.time_rank_string_cat_ordered 4.85ms ``` Closes pandas-dev#17981
1 parent 36c309e commit b551b28

File tree

2 files changed

+9
-1
lines changed

2 files changed

+9
-1
lines changed

pandas/core/categorical.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -900,7 +900,8 @@ def rename_categories(self, new_categories, inplace=False):
900900
inplace = validate_bool_kwarg(inplace, 'inplace')
901901
cat = self if inplace else self.copy()
902902

903-
if is_dict_like(new_categories):
903+
if (is_dict_like(new_categories) and
904+
not isinstance(new_categories, ABCSeries)):
904905
cat.categories = [new_categories.get(item, item)
905906
for item in cat.categories]
906907
else:

pandas/tests/test_categorical.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1203,6 +1203,13 @@ def test_rename_categories(self):
12031203
with pytest.raises(ValueError):
12041204
cat.rename_categories([1, 2])
12051205

1206+
def test_rename_categories_series(self):
1207+
# https://github.com/pandas-dev/pandas/issues/17981
1208+
result = pd.Categorical(['a', 'b']).rename_categories(
1209+
pd.Series([0, 1]))
1210+
expected = pd.Categorical([0, 1])
1211+
tm.assert_categorical_equal(result, expected)
1212+
12061213
def test_rename_categories_dict(self):
12071214
# GH 17336
12081215
cat = pd.Categorical(['a', 'b', 'c', 'd'])

0 commit comments

Comments
 (0)