Skip to main content
 首页 » 编程设计

python之传递 dtype= 'category' 的系列作为 Pandas 分类函数的类别

2025年04月02日9zdz8207

当我运行这段代码时,出现以下错误:

import pandas as pd 
 
car_colors = pd.Series(['Blue', 'Red', 'Green'], 
           dtype='category') 
 
car_data = pd.Categorical(['Yellow', 'Green', 'Red', 'Blue','Purple'], 
                              categories= car_colors, ordered=False) 
print car_colors 
s = pd.Series(car_data) 
s 

ValueError: object array method not producing an array

但有趣的是,当我删除 dtype = 'category' 时,代码工作正常。

简而言之,分类函数接受系列但不接受 dtype = 'category'

这是错误还是我做错了什么?

请您参考如下方法:

看起来需要将 tolist 添加到 Categorical 中的 categories :

car_colors = pd.Series(['Blue', 'Red', 'Green'], 
           dtype='category') 
 
car_data = pd.Categorical(['Yellow', 'Green', 'Red', 'Blue','Purple'], 
                              categories = car_colors.tolist(), ordered=False) 
 
s = pd.Series(car_data) 
print (s) 
 
0      NaN 
1    Green 
2      Red 
3     Blue 
4      NaN 
dtype: category 
Categories (3, object): [Blue, Red, Green] 

来自 EdChum's comment 的另一个解决方案正在使用cat.categories :

car_data = pd.Categorical(['Yellow', 'Green', 'Red', 'Blue','Purple'], 
                              categories = car_colors.cat.categories, ordered=False) 
s = pd.Series(car_data) 
print (s) 
0      NaN 
1    Green 
2      Red 
3     Blue 
4      NaN 
dtype: category 
Categories (3, object): [Blue, Green, Red]