Skip to content

Commit 38e1b9b

Browse files
authored
CLN: make Categorical.codes a simpler property (#33667)
1 parent 9376960 commit 38e1b9b

File tree

2 files changed

+12
-24
lines changed

2 files changed

+12
-24
lines changed

pandas/core/arrays/categorical.py

+11-23
Original file line numberDiff line numberDiff line change
@@ -199,17 +199,6 @@ def contains(cat, key, container):
199199
return any(loc_ in container for loc_ in loc)
200200

201201

202-
_codes_doc = """
203-
The category codes of this categorical.
204-
205-
Level codes are an array if integer which are the positions of the real
206-
values in the categories array.
207-
208-
There is not setter, use the other categorical methods and the normal item
209-
setter to change values in the categorical.
210-
"""
211-
212-
213202
class Categorical(ExtensionArray, PandasObject):
214203
"""
215204
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):
652641

653642
return cls(codes, dtype=dtype, fastpath=True)
654643

655-
def _get_codes(self):
644+
@property
645+
def codes(self) -> np.ndarray:
656646
"""
657-
Get the codes.
647+
The category codes of this categorical.
648+
649+
Codes are an array of integers which are the positions of the actual
650+
values in the categories array.
651+
652+
There is no setter, use the other categorical methods and the normal item
653+
setter to change values in the categorical.
658654
659655
Returns
660656
-------
661-
codes : integer array view
662-
A non writable view of the `codes` array.
657+
ndarray[int]
658+
A non-writable view of the `codes` array.
663659
"""
664660
v = self._codes.view()
665661
v.flags.writeable = False
666662
return v
667663

668-
def _set_codes(self, codes):
669-
"""
670-
Not settable by the user directly
671-
"""
672-
raise ValueError("cannot set Categorical codes directly")
673-
674-
codes = property(fget=_get_codes, fset=_set_codes, doc=_codes_doc)
675-
676664
def _set_categories(self, categories, fastpath=False):
677665
"""
678666
Sets new categories inplace

pandas/tests/arrays/categorical/test_api.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -464,7 +464,7 @@ def test_codes_immutable(self):
464464
tm.assert_numpy_array_equal(c.codes, exp)
465465

466466
# Assignments to codes should raise
467-
with pytest.raises(ValueError, match="cannot set Categorical codes directly"):
467+
with pytest.raises(AttributeError, match="can't set attribute"):
468468
c.codes = np.array([0, 1, 2, 0, 1], dtype="int8")
469469

470470
# changes in the codes array should raise

0 commit comments

Comments
 (0)