【问题标题】:iloc giving 'IndexError: single positional indexer is out-of-bounds'iloc 给出“IndexError:单个位置索引器超出范围”
【发布时间】:2017-08-02 00:49:36
【问题描述】:

我正在尝试使用以下代码对一些信息进行编码以读入机器学习模型

import numpy as np
import pandas as pd
import matplotlib.pyplot as py

Dataset = pd.read_csv('filename.csv', sep = ',')

X = Dataset.iloc[:,:-1].values
Y = Dataset.iloc[:,18].values

from sklearn.preprocessing import LabelEncoder, OneHotEncoder
labelencoder_X = LabelEncoder()
X[:, 0] = labelencoder_X.fit_transform(X[:, 0])
onehotencoder = OneHotEncoder(categorical_features = [0])
X = onehotencoder.fit_transform(X).toarray()

但是我收到一个错误

IndexError: single positional indexer is out-of-bounds

【问题讨论】:

    标签: python


    【解决方案1】:

    此错误是由以下原因引起的:

    Y = Dataset.iloc[:,18].values
    

    这里的索引超出范围很可能是因为您的数据集中的列少于 19 列,因此第 18 列不存在。您提供的以下代码根本没有使用 Y,因此您现在可以将这一行注释掉。

    【讨论】:

      【解决方案2】:

      当您使用大于dataframe 的尺寸的数字索引行/列时,会发生这种情况。例如,当你只有三列时获得第十一列。

      import pandas as pd
      
      df = pd.DataFrame({'Name': ['Mark', 'Laura', 'Adam', 'Roger', 'Anna'],
                         'City': ['Lisbon', 'Montreal', 'Lisbon', 'Berlin', 'Glasgow'],
                         'Car': ['Tesla', 'Audi', 'Porsche', 'Ford', 'Honda']})
      

      您有 5 行和三列

          Name      City      Car
      0   Mark    Lisbon    Tesla
      1  Laura  Montreal     Audi
      2   Adam    Lisbon  Porsche
      3  Roger    Berlin     Ford
      4   Anna   Glasgow    Honda
      

      让我们尝试索引第十一列(它不存在):

      df.iloc[:, 10] # there is obviously no 11th column
      

      IndexError: 单个位置索引器超出范围

      如果您是 Python 初学者,请记住 df.iloc[:, 10] 指的是第十一列。

      【讨论】:

        【解决方案3】:

        这对解决这里的问题没有帮助,但是无论谁可能来这里是为了错误而不是为了示例,当我尝试在 dataframe2 中查找一行时,我遇到了这个错误IndexError: single positional indexer is out-of-bounds 循环遍历dataframe1 的行,在 dataframe2 的过滤器中使用许多标准,并将每个找到的行添加到一个新的空 dataframe3 (不要问我为什么!)。该行中的一个值是 dataframe1 和 dataframe2 中的“nan”值。我无法再过滤,也无法添加新行。

        解决方案:

        dataframe1.fillna("nan") # or whatever you want as a fill value
        dataframe2.fillna("nan")
        

        并且脚本运行没有错误。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2019-03-21
          • 2018-03-03
          • 2019-09-24
          • 1970-01-01
          • 2016-10-23
          • 1970-01-01
          • 2020-11-26
          • 2023-03-30
          相关资源
          最近更新 更多