Skip to content

Commit 022aa9f

Browse files
committed
Allow for dict-like argument to Categorical.rename_categories
1 parent 37e23d0 commit 022aa9f

File tree

3 files changed

+18
-2
lines changed

3 files changed

+18
-2
lines changed

doc/source/whatsnew/v0.21.0.txt

+1-1
Original file line numberDiff line numberDiff line change
@@ -114,7 +114,7 @@ Other Enhancements
114114
- :func:`pd.read_sas()` now recognizes much more of the most frequently used date (datetime) formats in SAS7BDAT files (:issue:`15871`).
115115
- :func:`DataFrame.items` and :func:`Series.items` is now present in both Python 2 and 3 and is lazy in all cases (:issue:`13918`, :issue:`17213`)
116116
- :func:`Styler.where` has been implemented. It is as a convenience for :func:`Styler.applymap` and enables simple DataFrame styling on the Jupyter notebook (:issue:`17474`).
117-
117+
- :func:`Categorical.rename_categories` now accepts a dict-like argument as `new_categories`, and only updates the categories found in that dict. (:issue:`17336`)
118118

119119

120120
.. _whatsnew_0210.api_breaking:

pandas/core/categorical.py

+5-1
Original file line numberDiff line numberDiff line change
@@ -824,7 +824,11 @@ def rename_categories(self, new_categories, inplace=False):
824824
"""
825825
inplace = validate_bool_kwarg(inplace, 'inplace')
826826
cat = self if inplace else self.copy()
827-
cat.categories = new_categories
827+
if isinstance(new_categories, dict):
828+
cat.categories = [new_categories.get(item, item)
829+
for item in cat.categories]
830+
else:
831+
cat.categories = new_categories
828832
if not inplace:
829833
return cat
830834

pandas/tests/test_categorical.py

+12
Original file line numberDiff line numberDiff line change
@@ -983,6 +983,18 @@ def test_rename_categories(self):
983983
with pytest.raises(ValueError):
984984
cat.rename_categories([1, 2])
985985

986+
def test_rename_categories_dict(self):
987+
# GH 17336
988+
cat = pd.Categorical(['a', 'b', 'c', 'd'])
989+
res = cat.rename_categories({'a': 4, 'b': 3, 'c': 2, 'd': 1})
990+
expected = Index([4, 3, 2, 1])
991+
tm.assert_index_equal(res.categories, expected)
992+
# Test for inplace
993+
res = cat.rename_categories({'a': 4, 'b': 3, 'c': 2, 'd': 1},
994+
inplace=True)
995+
assert res is None
996+
tm.assert_index_equal(cat.categories, expected)
997+
986998
@pytest.mark.parametrize('codes, old, new, expected', [
987999
([0, 1], ['a', 'b'], ['a', 'b'], [0, 1]),
9881000
([0, 1], ['b', 'a'], ['b', 'a'], [0, 1]),

0 commit comments

Comments
 (0)