2015-09-04 68 views
2

我的代碼(從書Python Data Science Handbook(O'Reilly出版)):錯誤=真

披露:在寫作的時候,這本書仍處於早期發佈,這意味着它仍然未經編輯並且處於原始狀態。

import numpy as np 
import pandas as pd 
import seaborn as sns 
titanic = sns.load_dataset('titanic') 

titanic.pivot_table('survived', index='sex', columns='class') 

結果是:

Dataframe

但是,如果我現在嘗試添加使用margins關鍵字總數,出現以下錯誤:

titanic.pivot_table('survived', index='sex', columns='class', margins=True) 

TypeError: cannot insert an item into a CategoricalIndex that is not already an existing category 

任何想法可能造成這種情況?

版本信息:

  • 的Python 3.4.2
  • 大熊貓0.16.2
  • numpy的1.9.2
+0

這看起來像熊貓給我的錯誤。 –

+0

對於它的價值,它可以很好的使用python 2.7.10中的熊貓0.14.1和0.16.2 – Alexander

回答

5

這似乎是由於大熊貓0.15和0.16之間的變化。在以前的版本中,泰坦尼克號數據集有這個D型:

In [1]: import pandas, seaborn 

In [2]: pandas.__version__ 
'0.15.2' 

In [3]: titanic = seaborn.load_dataset('titanic') 

In [4]: titanic.dtypes 
Out[4]: 
survived   int64 
pclass   int64 
sex    object 
age   float64 
sibsp   int64 
parch   int64 
fare   float64 
embarked  object 
class   object 
who    object 
adult_male  bool 
deck   object 
embark_town  object 
alive   object 
alone    bool 
dtype: object 

隨着新的大熊貓:

In [1]: import pandas, seaborn 

In [2]: pandas.__version__ 
'0.16.2' 

In [3]: titanic = seaborn.load_dataset('titanic') 

In [4]: titanic.dtypes 
Out[4]: 
survived   int64 
pclass   int64 
sex    object 
age    float64 
sibsp    int64 
parch    int64 
fare   float64 
embarked   object 
class   category 
who    object 
adult_male   bool 
deck   category 
embark_town  object 
alive   object 
alone    bool 
dtype: object 

幾根柱子被自動轉換爲絕對的,這帶來了這個bug。這本書目前未發佈和未經編輯。我將確保使用最新版本進行測試,並在出版前修正這些類型的錯誤。

現在,這裏是一個解決辦法:

In [5]: titanic['class'] = titanic['class'].astype(object) 

In [6]: titanic.pivot_table('survived', index='sex', columns='class', margins=True) 
Out[6]: 
class  First Second  Third  All 
sex           
female 0.968085 0.921053 0.500000 0.742038 
male 0.368852 0.157407 0.135447 0.188908 
All  0.629630 0.472826 0.242363 0.383838 

編輯:我提出這個作爲一個問題來的大熊貓項目:https://github.com/pydata/pandas/issues/10989