【问题标题】: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]"

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

【问题讨论】:

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


    【解决方案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

        【讨论】:

          猜你喜欢
          • 2019-09-16
          • 1970-01-01
          • 2021-04-28
          • 2021-08-14
          • 2020-05-26
          • 2021-10-15
          • 1970-01-01
          • 2021-01-17
          • 1970-01-01
          相关资源
          最近更新 更多