Skip to main content
 首页 » 编程设计

python之Pandas CategoricalDtype : __new__() takes 1 positional argument but 2 were given

2025年01月19日9zhengyun_ustc

我正在阅读 pandas 文档,并按照 CategoricalIndex - MultiIndex / Advanced Indexing 上的第一个示例进行操作我有一个似乎来自 CategoricalDtype 类的错误。

这是代码(文档中的示例):

>>> import pandas as pd 
>>> import numpy as np 
>>> from pandas.api.types import CategoricalDtype 
>>> df = pd.DataFrame({'A': np.arange(6),'B': list('aabbca')}) 
>>> df 
   A  B 
0  0  a 
1  1  a 
2  2  b 
3  3  b 
4  4  c 
5  5  a 
 
>>> df['B'] = df['B'].astype(CategoricalDtype(list('cab'))) 
Traceback (most recent call last): 
  File "<stdin>", line 1, in <module> 
TypeError: __new__() takes 1 positional argument but 2 were given 

为了检查,我在控制台中输入了 pandas documentation - pandas.api.types.CategoricalDtype 中给出的示例但错误仍然存​​在:

>>> t = CategoricalDtype(categories=['b', 'a'], ordered=True) 
Traceback (most recent call last): 
  File "<stdin>", line 1, in <module> 
TypeError: __new__() got an unexpected keyword argument 'categories' 
>>> pd.Series(['a', 'b', 'a', 'c'], dtype=t) 
Traceback (most recent call last): 
  File "<stdin>", line 1, in <module> 
NameError: name 't' is not defined 

可能是 CategoricalDtype 类有问题还是我遗漏了什么?

请您参考如下方法:

这将在 Pandas 0.21+ 中正常工作。

对于旧版本,我们可以执行以下任一操作:

In [201]: df['B'].astype('category') 
Out[201]: 
0    a 
1    a 
2    b 
3    b 
4    c 
5    a 
Name: B, dtype: category 
Categories (3, object): [a, b, c] 

或:

In [202]: pd.Categorical(df['B'], categories=list('cab')) 
Out[202]: 
[a, a, b, b, c, a] 
Categories (3, object): [c, a, b]