pandas.Categorical#

class pandas.Categorical(values, categories=None, ordered=None, dtype=None, copy=True)[源代码]#

以经典 R / S-plus 的方式表示分类变量。

Categoricals 只能取有限的、通常是固定的可能值(categories)。与统计学上的分类变量不同,Categorical 可能具有顺序,但不能进行数值运算(加法、除法等)。

Categorical 的所有值都包含在 categories 中,或者为 np.nan。将不在 categories 中的值赋给它会引发 ValueError。顺序由 categories 的顺序决定,而不是值的字母顺序。

参数:
values类列表

分类变量的值。如果给定了类别,不在类别中的值将被替换为 NaN。

categories类索引(唯一),可选

此分类变量的唯一类别。如果未给出,则假定类别为 values 的唯一值(如果可能则排序,否则按它们出现的顺序排列)。

ordered布尔值,默认为 False

此分类变量是否被视为有序分类变量。如果为 True,则生成的分类变量将是有序的。有序分类变量在排序时会遵循其 categories 属性的顺序(该属性本身是 categories 参数,如果已提供)。

dtypeCategoricalDtype

一个 CategoricalDtype 实例,用于此分类变量。

copy布尔值,默认为 True

如果编码未更改,是否复制。

属性

categories

此分类数据的类别。

codes

此分类索引的类别代码。

ordered

类别是否具有排序关系。

dtype

此实例的 CategoricalDtype

Methods

from_codes(codes[, categories, ordered, ...])

根据代码和类别或数据类型创建 Categorical 类型。

as_ordered()

将 Categorical 设置为有序。

as_unordered()

将 Categorical 设置为无序。

set_categories(new_categories[, ordered, rename])

将类别设置为指定的新类别。

rename_categories(new_categories)

重命名类别。

reorder_categories(new_categories[, ordered])

按 new_categories 中指定的顺序重新排列类别。

add_categories(new_categories)

添加新类别。

remove_categories(removals)

删除指定的类别。

remove_unused_categories()

删除未使用的类别。

map(mapper[, na_action])

使用输入映射或函数映射类别。

__array__([dtype, copy])

NumPy 数组接口。

引发:
ValueError

如果类别不验证。

TypeError

如果明确给出了 ordered=True 但未给出 categoriesvalues 不可排序。

另请参阅

CategoricalDtype

分类数据的类型。

CategoricalIndex

具有底层 Categorical 的 Index。

注意

有关更多信息,请参阅 用户指南

示例

>>> 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, str): ['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, str): ['c' < 'b' < 'a']
>>> c.min()
'c'