pd.Categorical 和 pd.api.types.CategoricalDtype 之间的区别

问题描述 投票:0回答:1

我不明白

pd.Categorical
pd.api.types.CategoricalDtype
之间的区别。后者返回一个
CategoricalDType
实例,前者返回一个
Categories
实例。什么是
categories
对象?它们有何不同?它们有何关系?我什么时候应该使用其中一种而不是另一种?

type(pd.Categorical(['a','b'],ordered=True))
Out[187]: pandas.core.arrays.categorical.Categorical

type(pd.api.types.CategoricalDtype(['a','b'], ordered=True))
Out[188]: pandas.core.dtypes.dtypes.CategoricalDtype
python-3.x pandas categorical-data
1个回答
0
投票

您可以使用 pd.CategoricalDtype 将系列的数据类型更改为类别。

例如,您有如下字符串数据类型的系列:

s = pd.Series(['a', 'a', 'b', 'b'])

s.dtype
返回:

dtype('O')

现在,您可以使用以下命令创建分类数据类型:

s_dtype = pd.api.types.CategoricalDtype(['b','a'], ordered=True)

然后,您可以使用 pd.Series.astype 通过 b 排序来更改该数据 < a.

s.astype(s_dtype).sort_values()

输出:

2    b
3    b
0    a
1    a
dtype: category
Categories (2, object): ['b' < 'a']

哪里,

s = pd.Categorical(['a','b'],ordered=True)

是一个系列构造函数,其数据类型为分类数据类型。

© www.soinside.com 2019 - 2024. All rights reserved.