【问题标题】:Adding the last line of code results in this error: "in get_loc raise KeyError(key) from err". What causes this error?添加最后一行代码会导致此错误:“in get_loc raise KeyError(key) from err”。是什么导致了这个错误?
【发布时间】:2021-04-25 08:23:45
【问题描述】:

我正在尝试将日期从 2013 年到 2018 年,并添加代码的最后一行 Code 导致此错误 Error

为什么会发生这种情况,谁能告诉我是否有更好的方法来对日期进行子集化?

错误:

File "C:\Users\Dev\AppData\Local\Programs\Python\Python39\lib\site-packages\pandas\core\indexes\base.py", line 3080, in get_loc
    return self._engine.get_loc(casted_key)
  File "pandas\_libs\index.pyx", line 70, in pandas._libs.index.IndexEngine.get_loc
  File "pandas\_libs\index.pyx", line 101, in pandas._libs.index.IndexEngine.get_loc
  File "pandas\_libs\hashtable_class_helper.pxi", line 4554, in pandas._libs.hashtable.PyObjectHashTable.get_item
  File "pandas\_libs\hashtable_class_helper.pxi", line 4562, in pandas._libs.hashtable.PyObjectHashTable.get_item
KeyError: 'Date'

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "D:\Python Projects\MTE\Fitness Tracker\Analyze Your Runkeeper Fitness Data\datasets\Fitness Data.py", line 29, in <module>
    datesss=df_run[(df_run['Date'] > '01-01-2013') & (df_run['Date'] <= '31-12-2018')]
  File "C:\Users\Dev\AppData\Local\Programs\Python\Python39\lib\site-packages\pandas\core\frame.py", line 3024, in __getitem__
    indexer = self.columns.get_loc(key)
  File "C:\Users\Dev\AppData\Local\Programs\Python\Python39\lib\site-packages\pandas\core\indexes\base.py", line 3082, in get_loc
    raise KeyError(key) from err
KeyError: 'Date'

【问题讨论】:

  • 请不要粘贴您的代码、图片、edit 您的帖子并添加您的代码

标签: python pandas dataframe keyerror


【解决方案1】:

您的代码看起来正确,请检查您何时从 df_activities 创建 df_run 数据框,它具有“日期”列而不是索引,否则您将不得不 reset_index()。

错误提示 DataFrame(df_run) 要么不包含“日期”列,要么被设置为索引。

可以使用布尔掩码,与日期作为对象类型或时间戳类型一起使用:

解决方案

mask = (df['Date'] > '01-01-2013') & (df['Date'] <= '31-12-2019')
df.loc[mask]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-08-13
    • 2012-10-06
    • 2011-03-16
    • 2022-06-28
    • 2012-09-21
    • 2010-10-12
    • 2013-10-03
    相关资源
    最近更新 更多