首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >添加最后一行代码会导致以下错误:"in get_loc KeyError(key) from err“。是什么导致了这个错误?

添加最后一行代码会导致以下错误:"in get_loc KeyError(key) from err“。是什么导致了这个错误?
EN

Stack Overflow用户
提问于 2021-04-25 08:23:45
回答 1查看 8.7K关注 0票数 4

我正在尝试将2013年至2018年的日期进行子集,并将代码代码的最后一行添加到这个错误错误中。

为什么会发生这种情况,谁能告诉我是否有更好的方法来划分日期?

错误:

代码语言:javascript
运行
复制
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'
EN

回答 1

Stack Overflow用户

发布于 2021-04-25 08:40:05

您的代码看起来是正确的,请检查您何时从df_run创建df_activities数据,它有'Date‘列,而不是索引,否则您必须使用reset_index()。

错误表示DataFrame(df_run)要么不包含'Date‘列,要么设置为索引。

可以使用布尔掩码,使用日期作为对象类型或TimeStamp类型:

溶液

代码语言:javascript
运行
复制
mask = (df['Date'] > '01-01-2013') & (df['Date'] <= '31-12-2019')
df.loc[mask]
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67251245

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档