Skip to content

Commit

Permalink
DEPR: setting Categorical._codes (pandas-dev#41429)
Browse files Browse the repository at this point in the history
  • Loading branch information
jbrockmendel authored and JulianWgs committed Jul 3, 2021
1 parent 466ad50 commit 0e63f54
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 0 deletions.
1 change: 1 addition & 0 deletions doc/source/whatsnew/v1.3.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -644,6 +644,7 @@ Deprecations
- Deprecated the ``level`` keyword for :class:`DataFrame` and :class:`Series` aggregations; use groupby instead (:issue:`39983`)
- 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`)
- Deprecated :func:`merge` producing duplicated columns through the ``suffixes`` keyword and already existing columns (:issue:`22818`)
- Deprecated setting :attr:`Categorical._codes`, create a new :class:`Categorical` with the desired codes instead (:issue:`40606`)

.. ---------------------------------------------------------------------------
Expand Down
6 changes: 6 additions & 0 deletions pandas/core/arrays/categorical.py
Original file line number Diff line number Diff line change
Expand Up @@ -1861,6 +1861,12 @@ def _codes(self) -> np.ndarray:

@_codes.setter
def _codes(self, value: np.ndarray):
warn(
"Setting the codes on a Categorical is deprecated and will raise in "
"a future version. Create a new Categorical object instead",
FutureWarning,
stacklevel=2,
) # GH#40606
NDArrayBacked.__init__(self, value, self.dtype)

def _box_func(self, i: int):
Expand Down
9 changes: 9 additions & 0 deletions pandas/tests/arrays/categorical/test_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -489,6 +489,15 @@ def test_set_categories_inplace(self):

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

def test_codes_setter_deprecated(self):
cat = Categorical([1, 2, 3, 1, 2, 3, 3, 2, 1, 1, 1])
new_codes = cat._codes + 1
with tm.assert_produces_warning(FutureWarning):
# GH#40606
cat._codes = new_codes

assert cat._codes is new_codes


class TestPrivateCategoricalAPI:
def test_codes_immutable(self):
Expand Down

0 comments on commit 0e63f54

Please sign in to comment.