提升 KeyError(key) 错误来自 err KeyError: ‘fbs’ 在不同的数据集

我在尝试构建我的模型时,当我使用不同的数据集和不同的编码方式时,它能正常工作,但在另一段代码中,我使用了不同的编码方式和不同的数据集来构建我的模型,但似乎出现了这样的错误:

 Traceback (most recent call last):      File "C:\Users\user\AppData\Local\conda\conda\envs\myenv\lib\site-packages\pandas\core\indexes\base.py", line 3361, in get_loc        return self._engine.get_loc(casted_key)      File "pandas\_libs\index.pyx", line 76, in pandas._libs.index.IndexEngine.get_loc      File "pandas\_libs\index.pyx", line 108, in pandas._libs.index.IndexEngine.get_loc      File "pandas\_libs\hashtable_class_helper.pxi", line 5198, in pandas._libs.hashtable.PyObjectHashTable.get_item      File "pandas\_libs\hashtable_class_helper.pxi", line 5206, in pandas._libs.hashtable.PyObjectHashTable.get_item    KeyError: 'fbs'The above exception was the direct cause of the following exception:Traceback (most recent call last):  File "heart_disease.py", line 11, in <module>    dummy = pd.get_dummies(df[col], prefix=col)  File "C:\Users\user\AppData\Local\conda\conda\envs\myenv\lib\site-packages\pandas\core\frame.py", line 3455, in __getitem__    indexer = self.columns.get_loc(key)  File "C:\Users\user\AppData\Local\conda\conda\envs\myenv\lib\site-packages\pandas\core\indexes\base.py", line 3363, in get_loc    raise KeyError(key) from errKeyError: 'fbs'

我的代码有问题还是不同的数据集有问题?这是我的代码和我的数据集


回答:

问题在于列名并非你所期望的那样,因为它们包含了空格。

从你的代码来看:

# 你的 DataFramepenguins = pd.read_csv('file.csv')

打印

penguins.columns

返回

Index(['age', ' sex', ' cp', ' trestbps', ' chol', ' fbs', ' restecg',' thalach', ' exang', ' oldpeak', ' slope', ' thal', ' diagnosis'],dtype='object')

如你所见,列名中包含了空格。我们可以通过在读取文件后立即执行以下操作来解决这个问题:

penguins.columns = penguins.columns.str.replace(' ', '')

这将解决你的错误。

Related Posts

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注