【问题标题】:Problem when splitting data: KeyError: "None of [Int64Index([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13], dtype='int64')] are in the [columns]"拆分数据时出现问题:KeyError: "None of [Int64Index([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13], dtype='int64')] 在[列]"
【发布时间】:2021-11-05 22:58:31
【问题描述】:

我正在尝试对某些数据 wine.data 执行训练测试拆分,但是在初始化 x 和 y 时:

import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from sklearn.neural_network import MLPClassifier
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
from sklearn.preprocessing import StandardScaler

from sklearn.model_selection import cross_val_score

wine =  pd.read_csv("https://archive.ics.uci.edu/ml/machine-learning-databases/wine/wine.data")

print(wine.shape)
wine.head()
X = wine[np.arange(1,14)]
y = wine[0]

当我收到错误消息时,此段下面的其余代码将无法运行:

KeyError: "None of [Int64Index([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13], dtype='int64')] are in the [columns]"

我已尝试通过更改 X 值的范围或更改 np.arange 函数来解决此问题,但均无济于事。

任何帮助或建议将不胜感激,谢谢!

【问题讨论】:

  • 您的数据框具有以下列Index(['1', '14.23', '1.71', '2.43', '15.6', '127', '2.8', '3.06', '.28', '2.29', '5.64', '1.04', '3.92', '1065'], dtype='object') 所以.. 错误消息是正确的。您期望哪些列?
  • 我期待的列号是 0 到 13
  • 您应该打印您的数据框以查看它的外观...无论如何我已经发布了解决方案。

标签: python pandas numpy train-test-split


【解决方案1】:

您忘记将header=None 添加到数据框构造函数中。您正在下载的 csv 没有标题行。所以,如果不指定header=None,则第一行数据将作为表头。

试试

wine =  pd.read_csv(
    "https://archive.ics.uci.edu/ml/machine-learning-databases/wine/wine.data",
    header=None
)

【讨论】:

    【解决方案2】:

    您是否尝试按位置选择列? 如果是这样,请尝试:

    X = wine.iloc[:,np.arange(1,14)]
    y = wine.iloc[:, 0]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-05-30
      • 1970-01-01
      • 1970-01-01
      • 2022-10-08
      • 1970-01-01
      • 1970-01-01
      • 2021-02-15
      • 2019-07-23
      相关资源
      最近更新 更多