【问题标题】:getting raise KeyError(key) from err KeyError: 'fbs' in different dataset从 err KeyError: 'fbs' in different dataset 获取 raise KeyError(key)
【发布时间】:2021-11-10 11:44:13
【问题描述】:

我试图制作我的模型,当我使用不同的数据集和不同的编码时它可以工作,但在另一个代码中,我为我的模型使用不同的编码和不同的数据集,但它似乎显示如下错误:

 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 err
KeyError: 'fbs'

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

【问题讨论】:

    标签: python machine-learning random-forest


    【解决方案1】:

    问题在于列名不是您所期望的,因为它们包含空格。

    来自您的代码:

    # your DataFrame
    penguins = 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(' ', '')
    

    这将解决您的错误。

    【讨论】:

      猜你喜欢
      • 2019-05-01
      • 1970-01-01
      • 2021-01-06
      • 1970-01-01
      • 2017-09-27
      • 1970-01-01
      • 2018-01-10
      • 2021-05-24
      • 2019-10-18
      相关资源
      最近更新 更多