iloc give' IndexError:单个位置索引器超出界限'

时间:2017-03-11 19:01:52

标签: python machine-learning

我正在尝试使用以下

对一些信息进行编码以读入机器学习模型
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()

然而我收到的错误是

runfile('C:/Users/name/Desktop/Machine Learning/Data preprocessing      template.py', wdir='C:/Users/taylorr2/Desktop/Machine Learning')
Traceback (most recent call last):

  File "<ipython-input-141-a5d1cd02c2df>", line 1, in <module>
    runfile('C:/Users/name/Desktop/Machine Learning/Data preprocessing  template.py', wdir='C:/Users/taylorr2/Desktop/Machine Learning')

  File "C:\Users\name\AppData\Local\Continuum\Anaconda2\lib\site-packages\spyder\utils\site\sitecustomize.py", line 866, in runfile
    execfile(filename, namespace)

  File "C:\Users\name\AppData\Local\Continuum\Anaconda2\lib\site-packages\spyder\utils\site\sitecustomize.py", line 87, in execfile
exec(compile(scripttext, filename, 'exec'), glob, loc)

  File "C:/Users/name/Desktop/Machine Learning/Data preprocessing template.py", line 8, in <module>
Y = Dataset.iloc[:,18].values

   File "C:\Users\name\AppData\Local\Continuum\Anaconda2\lib\site-packages\pandas\core\indexing.py", line 1310, in __getitem__
return self._getitem_tuple(key)

   File "C:\Users\name\AppData\Local\Continuum\Anaconda2\lib\site-packages\pandas\core\indexing.py", line 1560, in _getitem_tuple
self._has_valid_tuple(tup)

   File "C:\Users\name\AppData\Local\Continuum\Anaconda2\lib\site-packages\pandas\core\indexing.py", line 151, in _has_valid_tuple
if not self._has_valid_type(k, i):

   File "C:\Users\name\AppData\Local\Continuum\Anaconda2\lib\site-packages\pandas\core\indexing.py", line 1528, in _has_valid_type
return self._is_valid_integer(key, axis)

   File "C:\Users\name\AppData\Local\Continuum\Anaconda2\lib\site-packages\pandas\core\indexing.py", line 1542, in _is_valid_integer
raise IndexError("single positional indexer is out-of-bounds")

IndexError: single positional indexer is out-of-bounds

我在这里读到了一个关于同样错误的问题,并尝试了

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

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

table = Dataset.find(id='AlerId')
rows = table.find_all('tr')[1:]
data = [[cell.text for cell in row.find_all('td')] for row in rows]
Dataset1 = pd.DataFrame(data=data, columns=columns)

X = Dataset1.iloc[:,:-1].values
Y = Dataset1.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()

但是我觉得这可能让我更加困惑,而现在更像是一个州。

有什么建议吗?

3 个答案:

答案 0 :(得分:34)

此错误由以下原因引起:

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

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

答案 1 :(得分:4)

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

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

让我们尝试为第11列编制索引(不存在):

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

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

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

答案 2 :(得分:-3)

延长CSV文件:添加更多行和列。文件很小时,它对我不起作用。我放纵了,现在可以了。