我不明白
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
您可以使用 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)
是一个系列构造函数,其数据类型为分类数据类型。