[英]Pandas: key error when passing margins=True in pivot_table
[英]Error when using Pandas pivot_table with margins=True
我的代码(摘自《 Python数据科学手册》 (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')
结果是:
但是,如果我现在尝试使用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
知道是什么原因造成的吗?
版本信息:
这似乎是由于熊猫0.15和0.16之间的变化所致。 在以前的版本中,泰坦尼克号数据集具有此dtype:
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
几列会自动转换为分类列,从而引发此错误。 该书目前尚未出版和编辑。 我一定会在发布之前测试一下最新版本并修复这些类型的错误。
目前,这是一种解决方法:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.