Python:pivot\u table和groupby得到完全相反的resu

2024-06-17 09:33:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在处理来自[seaborn]的数据集titanic。你知道吗

titanic = seaborn.load_dataset('titanic')

我把“年龄”一栏分成了分类栏。你知道吗

age = pd.cut(titanic['age'], [0, 18, 80])

然后问题来了,groupby和pivot表给出了完全不同的结果:

titanic.groupby(['sex', age, 'class'])['survived'].mean().unstack(-1)
titanic.pivot_table('survived', ['sex', age], 'class')

groupby and pivot_table results

一开始,我猜是因为nan在年龄,然后我用dropna处理的数据集来重做它。你知道吗

titanic = titanic.dropna()
age = pd.cut(titanic['age'], [0, 18, 80], right = True)
titanic.groupby(['sex', age, 'class'])['survived'].mean().unstack(-1)
titanic.pivot_table('survived', ['sex', age], 'class')

这次我甚至得到了完全不同的结果。你知道吗

groupby and pivot_table results after dropna

我的python版本是:python3.6.5::Anaconda,Inc。 熊猫:0.23.0

我的操作系统是MaxOS High Sierra 10.13.6

我再次尝试使用python3.7.0和pandas0.23.4,没有出现错误。你知道吗

result under python 3..7.0

所以我想知道是不是水蟒的虫子?你知道吗


Tags: 数据agetableseabornmeanclasspdpivot
2条回答

我发现是熊猫的一个bug,出现在0.23.0版本,2018年5月发布,在0.23.4版本,2018年9月发布解决。你知道吗

所以如果你遇到一些关于pandas.pivot\表,特别是当您的分类数据中存在nan时,最好先检查您的pandas版本并进行升级。:)

我试过你的陈述,得到了匹配的结果: enter image description here

相关问题 更多 >