KeyError:“ [Int64Index dtype ='int64',长度= 9313)中都没有[列]”

时间:2020-01-24 10:58:10

标签: python python-3.x pandas python-2.7 scikit-learn

具有323列和10348行的数据帧。我想使用以下代码使用分层k折除它

df= pd.read_csv("path")
 x=df.loc[:, ~df.columns.isin(['flag'])]
 y= df['flag']
StratifiedKFold(n_splits=5, random_state=None, shuffle=False)
for train_index, test_index in skf.split(x, y):
       print("TRAIN:", train_index, "TEST:", test_index)
       x_train, x_test = x[train_index], x[test_index]
       y_train, y_test = y[train_index], y[test_index]

但是出现以下错误

KeyError: "None of [Int64Index([    0,     1,     2,     3,     4,     5,     6,     7,     8,\n               10,\n            ...\n            10338, 10339, 10340, 10341, 10342, 10343, 10344, 10345, 10346,\n            10347],\n           dtype='int64', length=9313)] are in the [columns]"

有人告诉我为什么会出现此错误以及如何解决

3 个答案:

答案 0 :(得分:1)

似乎您有数据帧切片问题,而不是StratifiedKFold本身有问题。我为此目的设计了一个df,并使用 iloc 在此处切片索引数组来解决它:

from sklearn import model_selection

# The list of some column names in flag
flag = ["raw_sentence", "score"]
x=df.loc[:, ~df.columns.isin(flag)].copy()
y= df[flag].copy()
skf =model_selection.StratifiedKFold(n_splits=2, random_state=None, shuffle=False)
for train_index, test_index in skf.split(x, y):
    print("TRAIN:", train_index, "TEST:", test_index)
    x_train, x_test = x.iloc[list(train_index)], x.iloc[list(test_index)]

train_indexes和test_indexes是nd数组,有点把这里的工作弄乱了,我将它们转换为列表。

您可以参考:https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html

答案 1 :(得分:1)

您也可以使用 df.take(indices_list,axis=0)

x_train, x_test = x.take(list(train_index),axis=0), x.take(list(test_index),axis=0)

https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.take.html

答案 2 :(得分:0)

尝试将熊猫数据框更改为numpy数组,如下所示:

pd.DataFrame({"A": [1, 2], "B": [3, 4]}).to_numpy()

array([[1, 3],
       [2, 4]])