【问题标题】:Kaggle TypeError: slice indices must be integers or None or have an __index__ methodKaggle TypeError:切片索引必须是整数或无或具有 __index__ 方法
【发布时间】:2017-10-16 00:23:34
【问题描述】:

我正在尝试以这种方式在 Kaggle 笔记本上绘制 seaborn 直方图:

 sns.distplot(myseries, bins=50, kde=True)

但我收到此错误:

TypeError: slice indices must be integers or None or have an __index__ method

这是 Kaggle 笔记本: https://www.kaggle.com/asindico/slice-indices-must-be-integers-or-none/

这是系列头:

0     5850000
1     6000000
2     5700000
3    13100000
4    16331452
Name: price_doc, dtype: int64

【问题讨论】:

  • 你的系列是什么类型的?
  • @Kyle 我已经更新了问题
  • @Kyle 你是对的 kde=False 解决问题。如果您发布正确的答案,我可以为您分配赏金

标签: python pandas jupyter seaborn kaggle


【解决方案1】:

此错误似乎是一个已知问题。

https://github.com/mwaskom/seaborn/issues/1092

潜在解决方案 -> 将您的 statsmodels 包更新到 0.8.0

pip install -U statsmodels

【讨论】:

  • 它发生在 Kaggle 上......我无法卸载/更新任何东西
  • 如果您可以在没有 KDE 的情况下生存,它可能会避免这个错误。
  • @kyle 我已经看到其他 Kaggle 内核成功使用它
【解决方案2】:

正如@ryankdwyer 指出的那样,它是底层statsmodels 实现中的issue,在0.8.0 版本中不再存在。

由于 kaggle 不允许您从任何内核/脚本访问互联网,因此升级软件包不是一种选择。你基本上有以下两种选择:

  1. 使用sns.distplot(myseries, bins=50, kde=False)。这当然不会打印 kde。
  2. 使用来自版本0.8.0code 手动修补statsmodels 实现。诚然,这有点 hacky,但你会得到 kde 图。

这是一个例子(和一个proof on kaggle):

import numpy as np

def _revrt(X,m=None):
    """
    Inverse of forrt. Equivalent to Munro (1976) REVRT routine.
    """
    if m is None:
        m = len(X)
    i = int(m // 2+1)
    y = X[:i] + np.r_[0,X[i:],0]*1j
    return np.fft.irfft(y)*m

from statsmodels.nonparametric import kdetools

# replace the implementation with new method.
kdetools.revrt = _revrt

# import seaborn AFTER replacing the method. 
import seaborn as sns

# draw the distplot with the kde function
sns.distplot(myseries, bins=50, kde=True)

为什么有效?嗯,它与 Python 加载模块的方式有关。来自 Python docs

5.3.1。模块缓存

导入搜索期间检查的第一个位置是sys.modules。此映射用作先前已导入的所有模块的缓存,包括中间路径。因此,如果之前导入了 foo.bar.bazsys.modules 将包含 foofoo.barfoo.bar.baz 的条目。每个键都有对应的模块对象作为其值。

因此,from statsmodels.nonparametric import kdetools 在此模块缓存中。下次 seaborn 获取它时,缓存的版本将由 Python 模块加载器返回。由于这个缓存版本是我们适配的模块,所以使用了我们的revrt函数补丁。顺便说一句,这种做法在编写单元测试时非常方便,被称为 mocking

【讨论】:

    【解决方案3】:

    来自@ryankdwyer 的seaborn 问题,这听起来像是kde 中的一个错误。尝试使用 kde=False 将其关闭。

     sns.distplot(myseries, bins=50, kde=False)
    

    【讨论】:

      猜你喜欢
      • 2017-07-27
      • 2015-04-01
      • 2018-06-06
      • 2018-09-21
      • 2020-07-01
      • 2021-08-21
      • 1970-01-01
      • 2014-01-11
      • 2022-08-11
      相关资源
      最近更新 更多