我不明白为什么我在运行以下代码时出现错误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数据框)拆分了我cv.split(X)
。
X.shape
y.shape
Out: (13503, 17)
Out: (13503,)
答案 0 :(得分:14)
问题是您尝试使用X
为X[train_index]
编制索引的方式。
由于您有.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
df = df.values
#now this should work fine
df[[1,2]]
#array([[25, 97, 78, 74],
# [ 6, 84, 16, 21]])