[英]Class in python:KeyError line 2897, in get_loc raise KeyError(key) from err
[英]Adding the last line of code results in this error: "in get_loc raise KeyError(key) from err". What causes this error?
我正在尝试将日期从 2013 年到 2018 年进行子集化,并添加代码的最后一行代码会导致此错误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'
您的代码看起来正确,您能否检查一下您何时从 df_activities 创建 df_run Dataframe,它具有“日期”列而不是索引,否则您将不得不重置索引()。
错误表明 DataFrame(df_run) 要么不包含“日期”列,要么被设置为索引。
可以使用 Boolean 掩码,日期为 object 类型或时间戳类型:
解决方案
mask = (df['Date'] > '01-01-2013') & (df['Date'] <= '31-12-2019')
df.loc[mask]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.