2016-09-13 20 views
2

當我運行這段代碼,我得到了以下錯誤:與D型=「類」傳遞系列作爲類別熊貓範疇功能

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'

它是一個錯誤還是我做錯了什麼?

+0

我想這沒有任何意義,重新做一個明確的當數據已經有dtype的類別,所以這是一個錯誤在某種意義上,但也有點奇怪,想要這樣做 – EdChum

+0

如果你明確地只傳遞類別,那麼它的作品:'car_data = pd.Categorical(['Yellow','Green','Red','Blue','Purple'], categories = car_colors.cat.categories,ordered = False)' – EdChum

+0

是的,那完全是我的疑問。我們可以將列表和系列作爲類別傳遞,而不是類別本身。感謝您清理EdChum –

回答

1

它看起來像在需要添加Categoricaltolistcategories

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]