Skip to content

Commit 9a6c13d

Browse files
authored
DEPR: setting Categorical._codes (#41429)
1 parent 130ce53 commit 9a6c13d

File tree

3 files changed

+16
-0
lines changed

3 files changed

+16
-0
lines changed

doc/source/whatsnew/v1.3.0.rst

+1
Original file line numberDiff line numberDiff line change
@@ -644,6 +644,7 @@ Deprecations
644644
- Deprecated the ``level`` keyword for :class:`DataFrame` and :class:`Series` aggregations; use groupby instead (:issue:`39983`)
645645
- The ``inplace`` parameter of :meth:`Categorical.remove_categories`, :meth:`Categorical.add_categories`, :meth:`Categorical.reorder_categories`, :meth:`Categorical.rename_categories`, :meth:`Categorical.set_categories` is deprecated and will be removed in a future version (:issue:`37643`)
646646
- Deprecated :func:`merge` producing duplicated columns through the ``suffixes`` keyword and already existing columns (:issue:`22818`)
647+
- Deprecated setting :attr:`Categorical._codes`, create a new :class:`Categorical` with the desired codes instead (:issue:`40606`)
647648

648649
.. ---------------------------------------------------------------------------
649650

pandas/core/arrays/categorical.py

+6
Original file line numberDiff line numberDiff line change
@@ -1861,6 +1861,12 @@ def _codes(self) -> np.ndarray:
18611861

18621862
@_codes.setter
18631863
def _codes(self, value: np.ndarray):
1864+
warn(
1865+
"Setting the codes on a Categorical is deprecated and will raise in "
1866+
"a future version. Create a new Categorical object instead",
1867+
FutureWarning,
1868+
stacklevel=2,
1869+
) # GH#40606
18641870
NDArrayBacked.__init__(self, value, self.dtype)
18651871

18661872
def _box_func(self, i: int):

pandas/tests/arrays/categorical/test_api.py

+9
Original file line numberDiff line numberDiff line change
@@ -489,6 +489,15 @@ def test_set_categories_inplace(self):
489489

490490
tm.assert_index_equal(cat.categories, Index(["a", "b", "c", "d"]))
491491

492+
def test_codes_setter_deprecated(self):
493+
cat = Categorical([1, 2, 3, 1, 2, 3, 3, 2, 1, 1, 1])
494+
new_codes = cat._codes + 1
495+
with tm.assert_produces_warning(FutureWarning):
496+
# GH#40606
497+
cat._codes = new_codes
498+
499+
assert cat._codes is new_codes
500+
492501

493502
class TestPrivateCategoricalAPI:
494503
def test_codes_immutable(self):

0 commit comments

Comments
 (0)