pandas.Categorical.from_codes#

classmethod Categorical.from_codes(codes, categories=None, ordered=None, dtype=None, validate=True)[源代码]#

从代码和分类或 dtype 创建 Categorical 类型。

如果您已经有了 codes 和 categories/dtype,则此构造函数很有用,因此不需要(计算密集型)因子化步骤,该步骤通常在构造函数中完成。

如果您的数据不遵循此约定,请使用正常构造函数。

Parameters:
codesarray-like of int

一个整数数组,其中每个整数指向 categories 或 dtype.categories 中的一个类别,否则为 NaN(-1)。

categoriesindex-like, optional

类别的类别。项必须是唯一的。如果此处未给出类别,则必须在 dtype 中提供。

orderedbool, optional

此类别是否被视为有序类别。如果此处或 dtype 中未给出,则生成的类别将是无序的。

dtypeCategoricalDtype 或 “category”, optional

如果为 CategoricalDtype ,则不能与 categoriesordered 一起使用。

validatebool, default True

如果为 True,则验证 codes 是否对 dtype 有效。如果为 False,则不验证 codes 是否有效。请谨慎跳过验证,因为无效的 codes 可能导致严重问题,例如段错误。

在 2.1.0 版本加入.

Returns:
Categorical

Examples

>>> dtype = pd.CategoricalDtype(['a', 'b'], ordered=True)
>>> pd.Categorical.from_codes(codes=[0, 1, 0, 1], dtype=dtype)
['a', 'b', 'a', 'b']
Categories (2, object): ['a' < 'b']