Skip to content

CLN: make Categorical.codes a simpler property #33667

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Apr 20, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 11 additions & 23 deletions pandas/core/arrays/categorical.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion pandas/tests/arrays/categorical/test_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down