Pandas和scikit学习:keyrerror:[...]不在索引中

2024-05-02 08:10:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我不明白为什么运行以下代码时会出现错误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,)

Tags: 代码intestindex错误nottrainout
1条回答
网友
1楼 · 发布于 2024-05-02 08:10:20

问题是您试图使用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]

第1种方式:使用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]])

相关问题 更多 >