Python iloc 给出“IndexError:单个位置索引器越界”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42739327/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 22:05:04  来源:igfitidea点击:

iloc giving 'IndexError: single positional indexer is out-of-bounds'

python

提问by Taylrl

I am trying to encode some information to read into a Machine Learning model using the following

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

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()

however I am getting an error that reads

但是我收到一个错误消息

IndexError: single positional indexer is out-of-bounds

回答by slonopotam

This error is caused by:

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

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

Indexing is out of bounds here most probably because there are less than 19 columns in your Dataset, so column 18 does not exist. The following code you provided doesn't use Y at all, so you can just comment out this line for now.

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

回答by Nicolas Gervais

This happens when you index a row/column with a number that is larger than the dimensions of your dataframe. For instance, getting the eleventh column when you have only three.

当您索引行/列的数字大于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']})

You have 5 rows and three columns:

您有 5 行和3 列

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

Let's try to index the eleventh column(it doesn't exist):

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

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

IndexError: single positional indexer is out-of-bounds

IndexError:单个位置索引器越界

If you are a beginner with Python, remember that df.iloc[:, 10]would refer to the eleventh column.

如果您是 Python 初学者,请记住df.iloc[:, 10]将参考第十一栏。

回答by Qalb E Abbas

Lenghten your CSV file: add more rows and columns. It was not working for me when file was small. I lenghtened and now it worked.

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