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

时间:2017-05-16 19:05:26

标签: python pandas jupyter seaborn kaggle

我试图以这种方式在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

3 个答案:

答案 0 :(得分:5)

正如@ryankdwyer所指出的那样,statsmodels实施中的issuecode0.8.0版已不再存在。

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

  1. 使用sns.distplot(myseries, bins=50, kde=False)。这当然不会打印kde。
  2. 使用版本statsmodels中的proof on kaggle手动修补0.8.0实施。不可否认,这有点hacky,但你会得到kde情节。
  3. 以下是一个示例(和docs):

    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 this

      

    <强> 5.3.1。模块缓存

         

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

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

答案 1 :(得分:2)

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

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

潜在解决方案 - &gt;将statsmodels包更新为0.8.0

pip install -U statsmodels

答案 2 :(得分:0)

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

InputStream