Pandas 和 scikit-learn:KeyError:[....] 不在索引中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/51091132/
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-09-14 05:45:29  来源:igfitidea点击:

Pandas and scikit-learn: KeyError: [....] not in index

pythonpandasscikit-learn

提问by ScalaBoy

I do not understand why do I get the error KeyError: '[ 1351 1352 1353 ... 13500 13501 13502] not in index'when I run this code:

我不明白为什么KeyError: '[ 1351 1352 1353 ... 13500 13501 13502] not in index'运行此代码时会出现错误:

cv = KFold(n_splits=10)

for train_index, test_index in cv.split(X):
    f_train_X, f_valid_X = X[train_index], X[test_index]
    f_train_y, f_valid_y = y[train_index], y[test_index]

I use X(a Pandas dataframe) to split I cv.split(X).

我使用X(一个 Pandas 数据框)来分割 I cv.split(X)

X.shape
y.shape
Out: (13503, 17)
Out: (13503,)

回答by seralouk

The problem is the way you are trying to index the Xusing X[train_index].You need to use .locor .ilocsince you have pandasdataframe.

问题在于您尝试索引Xusing 的方式X[train_index]您需要使用.loc.iloc因为您有pandas数据框。



Use this

用这个

cv = KFold(n_splits=10)

for train_index, test_index in cv.split(X):
    f_train_X, f_valid_X = X.iloc[train_index], X.iloc[test_index]
    f_train_y, f_valid_y = y.iloc[train_index], y.iloc[test_index]

1st way: Example using iloc

第一种方式:使用示例 iloc

import pandas as pd
import numpy as np

df = pd.DataFrame(np.random.randint(0,100,size=(100, 4)), columns=list('ABCD'))

df[[1,2]]
#KeyError: '[1 2] not in index'

df.iloc[[1,2]]
#    A   B   C   D
#1  25  97  78  74
#2   6  84  16  21

2nd way: Example by converting pandas to numpy in advance

第二种方式:例如提前将pandas转换为numpy

df = df.values

#now this should work fine
df[[1,2]]
#array([[25, 97, 78, 74],
#      [ 6, 84, 16, 21]])