KeyError:“[Int64Index dtype='int64', length=9313)] 都不在 [columns] 中”

Posted

技术标签:

【中文标题】KeyError:“[Int64Index dtype=\'int64\', length=9313)] 都不在 [columns] 中”【英文标题】:KeyError: "None of [Int64Index dtype='int64', length=9313)] are in the [columns]"KeyError:“[Int64Index dtype='int64', length=9313)] 都不在 [columns] 中” 【发布时间】:2020-05-10 16:47:45 【问题描述】:

有一个 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]"

任何人告诉我为什么我会得到这个错误以及如何解决它

【问题讨论】:

【参考方案1】:

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

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

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

【讨论】:

【参考方案2】:

似乎您遇到了数据框切片问题,而不是 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-arrays 有点搞乱这里的工作,我将它们转换为列表。

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

【讨论】:

【参考方案3】:

你也可以使用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

【讨论】:

以上是关于KeyError:“[Int64Index dtype='int64', length=9313)] 都不在 [columns] 中”的主要内容,如果未能解决你的问题,请参考以下文章

为啥 str(KeyError) 添加额外的引号?

为啥我收到此错误? KeyError:“没有”

KeyError : 0 熊猫

KeyError:'plotly_domain'

python3 日志检索异常抛出异常 raise KeyError(key),KeyError: 'formatters'

python里出现keyerror 怎么解决