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

Sca*_*Boy 8 python pandas 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]
Run Code Online (Sandbox Code Playgroud)

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

X.shape
y.shape
Out: (13503, 17)
Out: (13503,)
Run Code Online (Sandbox Code Playgroud)

mak*_*kis 17

问题是您尝试索引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]
Run Code Online (Sandbox Code Playgroud)

第一种方式:使用示例 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
Run Code Online (Sandbox Code Playgroud)

第二种方式:通过提前将pandas转换为numpy的示例

df = df.values

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