【问题标题】:Python: pivot_table and groupby get totally opposite resultPython:pivot_table 和 groupby 得到完全相反的结果
【发布时间】:2019-02-26 17:10:14
【问题描述】:

我正在处理来自 [seaborn] 的数据集 titanic

titanic = seaborn.load_dataset('titanic')

我将年龄列分成分类箱。

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

那么问题来了,groupby 和 pivot_table 给出完全不同的结果:

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

groupby and pivot_table results

一开始我猜是因为age里面的nan,后来我用dropna处理的dataset重做了。

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版本是:Python 3.6.5 :: Anaconda, Inc. 熊猫:0.23.0

我的操作系统是 MaxOS High Sierra 10.13.6

我用python 3.7.0和pandas 0.23.4再次尝试,没有出现错误。

result under python 3..7.0

所以我想知道这是否是 Anaconda 的错误?

【问题讨论】:

  • 我试过很多次了,这个bug只出现在Python 3.6.5下 :: Anaconda, Inc. pandas: 0.23.0
  • 如果你用 Python 3.6.6:: Anaconda, Inc. pandas:0.23.4 创建一个新环境,这个 bug 就会消失。
  • 终于发现是pandas的bug,0.23.0版本出现,0.23.4版本解决。
  • 因为你解决了你的问题,你应该写一个回答你的问题并接受它。这样您的问题将显示为已解决。

标签: python pandas anaconda pivot-table pandas-groupby


【解决方案1】:

发现是pandas的一个bug,出现在2018年5月发布的0.23.0版本,在2018年9月发布的0.23.4版本中解决。

所以如果你碰巧遇到了关于pandas.pivot_table的一些问题,特别是当你的分类数据中存在NaN时,你最好先检查你的pandas版本并升级它。:)

【讨论】:

    【解决方案2】:

    我尝试了您的陈述并得到了匹配的结果: enter image description here

    【讨论】:

    • 感谢您的回复。你能告诉我你的 Python 版本和 Pandas 版本吗?
    • 我在命令行中用python 3.7.0再次尝试,结果匹配。那我觉得anaconda有问题:(
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-10
    • 1970-01-01
    • 2016-11-12
    • 2018-04-13
    • 1970-01-01
    相关资源
    最近更新 更多