pandas.Categorical#
- class pandas.Categorical(values, categories=None, ordered=None, dtype=None, fastpath=_NoDefault.no_default, copy=True)[源代码]#
以经典的 R / S-plus 风格表示分类变量。
Categoricals 只能接受有限的、通常是固定的可能值 (categories)。与统计分类变量相反,Categorical 可能有一个顺序,但不能进行数值运算(加法、除法等)。
Categorical 的所有值要么在 categories 中,要么是 np.nan。分配不在 categories 中的值将引发 ValueError。顺序由 categories 的顺序定义,而不是值的词典顺序。
- Parameters:
- values类似列表
分类的值。如果提供了 categories,则不在 categories 中的值将被替换为 NaN。
- categories类似 Index(唯一),可选
该分类的唯一分类。如果未给出,则假定分类是 values 的唯一值(如果可能则排序,否则按它们出现的顺序)。
- orderedbool,默认 False
该分类是否被视为有序分类。如果为 True,则生成的分类将被排序。有序分类在排序时会遵循其 categories 属性的顺序(该属性又是由提供的 categories 参数决定的)。
- dtypeCategoricalDtype
用于此分类的
CategoricalDtype实例。
- Raises:
- ValueError
如果分类未通过验证。
- TypeError
如果显式给出
ordered=True但没有 categories,并且 values 不可排序。
参见
CategoricalDtype分类数据类型。
CategoricalIndex具有底层
Categorical的 Index。
Notes
有关更多信息,请参阅 user guide 。
Examples
>>> pd.Categorical([1, 2, 3, 1, 2, 3]) [1, 2, 3, 1, 2, 3] Categories (3, int64): [1, 2, 3]
>>> pd.Categorical(['a', 'b', 'c', 'a', 'b', 'c']) ['a', 'b', 'c', 'a', 'b', 'c'] Categories (3, object): ['a', 'b', 'c']
缺失值不包含在分类中。
>>> c = pd.Categorical([1, 2, 3, 1, 2, 3, np.nan]) >>> c [1, 2, 3, 1, 2, 3, NaN] Categories (3, int64): [1, 2, 3]
但是,它们的存在通过 codes 属性中的代码 -1 来指示。
>>> c.codes array([ 0, 1, 2, 0, 1, 2, -1], dtype=int8)
有序 Categoricals 可以根据分类的自定义顺序进行排序,并且可以具有最小值和最大值。
>>> c = pd.Categorical(['a', 'b', 'c', 'a', 'b', 'c'], ordered=True, ... categories=['c', 'b', 'a']) >>> c ['a', 'b', 'c', 'a', 'b', 'c'] Categories (3, object): ['c' < 'b' < 'a'] >>> c.min() 'c'
Attributes
此分类的分类。
此分类索引的分类代码。
分类是否具有有序关系。
此实例 the
CategoricalDtype。Methods
from_codes(codes[, categories, ordered, ...])从代码和分类或 dtype 创建 Categorical 类型。
__array__([dtype, copy])numpy 数组接口。