diff --git a/pandas/core/arrays/categorical.py b/pandas/core/arrays/categorical.py index c5cac0cfeef6c..cdd0717849e96 100644 --- a/pandas/core/arrays/categorical.py +++ b/pandas/core/arrays/categorical.py @@ -199,17 +199,6 @@ def contains(cat, key, container): return any(loc_ in container for loc_ in loc) -_codes_doc = """ -The category codes of this categorical. - -Level codes are an array if integer which are the positions of the real -values in the categories array. - -There is not setter, use the other categorical methods and the normal item -setter to change values in the categorical. -""" - - class Categorical(ExtensionArray, PandasObject): """ Represent a categorical variable in classic R / S-plus fashion. @@ -652,27 +641,26 @@ def from_codes(cls, codes, categories=None, ordered=None, dtype=None): return cls(codes, dtype=dtype, fastpath=True) - def _get_codes(self): + @property + def codes(self) -> np.ndarray: """ - Get the codes. + The category codes of this categorical. + + Codes are an array of integers which are the positions of the actual + values in the categories array. + + There is no setter, use the other categorical methods and the normal item + setter to change values in the categorical. Returns ------- - codes : integer array view - A non writable view of the `codes` array. + ndarray[int] + A non-writable view of the `codes` array. """ v = self._codes.view() v.flags.writeable = False return v - def _set_codes(self, codes): - """ - Not settable by the user directly - """ - raise ValueError("cannot set Categorical codes directly") - - codes = property(fget=_get_codes, fset=_set_codes, doc=_codes_doc) - def _set_categories(self, categories, fastpath=False): """ Sets new categories inplace diff --git a/pandas/tests/arrays/categorical/test_api.py b/pandas/tests/arrays/categorical/test_api.py index 691230620c2e8..6fce4b4145ff2 100644 --- a/pandas/tests/arrays/categorical/test_api.py +++ b/pandas/tests/arrays/categorical/test_api.py @@ -464,7 +464,7 @@ def test_codes_immutable(self): tm.assert_numpy_array_equal(c.codes, exp) # Assignments to codes should raise - with pytest.raises(ValueError, match="cannot set Categorical codes directly"): + with pytest.raises(AttributeError, match="can't set attribute"): c.codes = np.array([0, 1, 2, 0, 1], dtype="int8") # changes in the codes array should raise