pd.Categorical 和 pd.api.types.CategoricalDtype

Difference between pd.Categorical and pd.api.types.CategoricalDtype

提问人:PKB 提问时间:10/24/2023 最后编辑:PKB 更新时间:10/30/2023 访问量:47

问:

编辑

根据到目前为止的答案(谢谢),我了解它是什么以及它的用途。/ 分类数组有什么用?它有一个常见的用例吗?CategoricalDTypeCategorical

--

我不明白 和 之间的区别。后者返回一个实例,前者返回一个实例。什么是对象?它们有何不同?它们有什么关系?什么时候应该使用一个而不是另一个?pd.Categoricalpd.api.types.CategoricalDtypeCategoricalDTypeCategoriesCategorical

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 分类数据

评论


答:

4赞 Scott Boston 10/24/2023 #1

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

例如,你有字符串 dtype 的系列,如下所示:

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

s.dtype返回:

dtype('O')

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

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

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

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)

是一个分类数组构造函数。

3赞 mozway 10/24/2023 #2

为了补充@Scott的答案,当您希望在不同对象之间维护公共 Categorical 时,CategoricalDtype 非常有用。

让我们考虑一下:

s1 = pd.Series(['a', 'a', 'b', 'b'])
s2 = pd.Series(['a', 'c', 'b', 'b'])

如果我们转换为通用的 Categorical 和 ,则生成的 Series 将回退到对象,因为类别不常见:concat

out1 = pd.concat([s1.astype('category'),
                  s2.astype('category')])

0    a
1    a
2    b
3    b
0    a
1    c
2    b
3    b
dtype: object

现在使用一个通用的确保在组合系列后保持这个dtype:CategoricalDtype

cat = pd.CategoricalDtype(['a', 'b', 'c'])
out2 = pd.concat([s1.astype(cat),
                  s2.astype(cat)])

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

其他示例:

cat = pd.CategoricalDtype(['a', 'b', 'c'], ordered=True)
out = s1.astype(cat) < s2.astype(cat)

0    False
1     True
2    False
3    False
dtype: bool

评论

0赞 Scott Boston 10/24/2023
谢谢你,@mozway。我很欣赏你的扩展和解释,并举了一个很好的例子。+1