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

标签 python pandas machine-learning scikit-learn

我不明白为什么在运行此代码时会出现错误 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]

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

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

最佳答案

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


使用这个

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]

第一种方式:使用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

方式二:先将pandas转成numpy的例子

df = df.values

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

关于python - Pandas 和 scikit-learn : KeyError: [. ...] 不在索引中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51091132/

相关文章:

python - TfidfVectorizer 和 SelectPercentile 返回什么?

image - 过滤 numpy 数组并将数组重新堆叠为多维矩阵

python : group elements together in list

javascript - 如何在 javascript 中使用 python 变量?

python - 按顺序依次读取文件

python - 如何在 wordnet 词典中添加新词?

python - pandas 数据帧的向量化操作

python - 为某些列 pandas 创建新列

python - 如何复制行但在 Pandas 中交换值

python - 稀疏字符串分类的 Scikit-learn 朴素贝叶斯莫名其妙的结果