Kaggle TypeError:切片索引必须是整数或无或具有__index__方法

Sin*_*ico 6 python pandas seaborn jupyter kaggle

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

 sns.distplot(myseries, bins=50, kde=True)
Run Code Online (Sandbox Code Playgroud)

但我得到这个错误:

TypeError: slice indices must be integers or None or have an __index__ method
Run Code Online (Sandbox Code Playgroud)

这是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
Run Code Online (Sandbox Code Playgroud)

Jan*_*nes 6

正如@ryankdwyer指出的那样,这是底层实现中的一个问题,statsmodels0.8.0发布中不再存在.

由于kaggle不允许您从任何内核/脚本访问Internet,因此无法升级软件包.您基本上有以下两种选择:

  1. 使用sns.distplot(myseries, bins=50, kde=False).这当然不会打印kde.
  2. statsmodels使用版本中的代码手动修补实现0.8.0.不可否认,这有点hacky,但你会得到kde情节.

这是一个例子(和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)
Run Code Online (Sandbox Code Playgroud)

它为什么有效?嗯,它与Python加载模块的方式有关.从Python 文档:

5.3.1.模块缓存

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

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