Make a Categorical type from codes and categories or dtype. This constructor is useful if you already have codes and categories/dtype and so do not need the (computation intensive) factorization step, which is usually done on the constructor. If your data d
(
cls,
codes,
categories=None,
ordered=None,
dtype: Dtype | None = None,
validate: bool = True,
)
| 714 | |
| 715 | @classmethod |
| 716 | def from_codes( |
| 717 | cls, |
| 718 | codes, |
| 719 | categories=None, |
| 720 | ordered=None, |
| 721 | dtype: Dtype | None = None, |
| 722 | validate: bool = True, |
| 723 | ) -> Self: |
| 724 | """ |
| 725 | Make a Categorical type from codes and categories or dtype. |
| 726 | |
| 727 | This constructor is useful if you already have codes and |
| 728 | categories/dtype and so do not need the (computation intensive) |
| 729 | factorization step, which is usually done on the constructor. |
| 730 | |
| 731 | If your data does not follow this convention, please use the normal |
| 732 | constructor. |
| 733 | |
| 734 | Parameters |
| 735 | ---------- |
| 736 | codes : array-like of int |
| 737 | An integer array, where each integer points to a category in |
| 738 | categories or dtype.categories, or else is -1 for NaN. |
| 739 | categories : index-like, optional |
| 740 | The categories for the categorical. Items need to be unique. |
| 741 | If the categories are not given here, then they must be provided |
| 742 | in `dtype`. |
| 743 | ordered : bool, optional |
| 744 | Whether or not this categorical is treated as an ordered |
| 745 | categorical. If not given here or in `dtype`, the resulting |
| 746 | categorical will be unordered. |
| 747 | dtype : CategoricalDtype or "category", optional |
| 748 | If :class:`CategoricalDtype`, cannot be used together with |
| 749 | `categories` or `ordered`. |
| 750 | validate : bool, default True |
| 751 | If True, validate that the codes are valid for the dtype. |
| 752 | If False, don't validate that the codes are valid. Be careful about skipping |
| 753 | validation, as invalid codes can lead to severe problems, such as segfaults. |
| 754 | |
| 755 | .. versionadded:: 2.1.0 |
| 756 | |
| 757 | Returns |
| 758 | ------- |
| 759 | Categorical |
| 760 | |
| 761 | See Also |
| 762 | -------- |
| 763 | codes : The category codes of the categorical. |
| 764 | CategoricalIndex : An Index with an underlying ``Categorical``. |
| 765 | |
| 766 | Examples |
| 767 | -------- |
| 768 | >>> dtype = pd.CategoricalDtype(["a", "b"], ordered=True) |
| 769 | >>> pd.Categorical.from_codes(codes=[0, 1, 0, 1], dtype=dtype) |
| 770 | ['a', 'b', 'a', 'b'] |
| 771 | Categories (2, str): ['a' < 'b'] |
| 772 | """ |
| 773 | dtype = CategoricalDtype._from_values_or_dtype( |