【问题标题】:Pandas index.get_loc giving keyerror for time series dataPandas index.get_loc 为时间序列数据提供 keyerror
【发布时间】:2018-09-03 11:57:46
【问题描述】:

以下代码可以正常工作。

import pandas as pd
#import numpy as np 
 import matplotlib.pyplot as plt 
 from IPython import get_ipython 
 get_ipython().run_line_magic('matplotlib', 'inline')

sym = 'SPY' 
df_close = pd.DataFrame() 
df_temp = pd.read_json('https://api.iextrading.com/1.0/stock/'+sym+'/chart/5y') 
df_temp.set_index('date',inplace=True) 
df_close = df_temp['close']

loc = df_close.index.get_loc('2015-08-17')

我修改它以从 nsepy 包中获取数据。即替换 read_json 行并注释 set_index 行,因为从包中获取的数据默认将日期行作为索引

import pandas as pd
#import numpy as np
import matplotlib.pyplot as plt
from IPython import get_ipython
from datetime import date
from nsepy import get_history

get_ipython().run_line_magic('matplotlib', 'inline')

sym = 'SBIN'
df_close = pd.DataFrame()
df_temp = get_history(symbol=sym,
                   start=date(2014,1,1),
                   end=date(2018,3,24))
#df_temp.set_index('date',inplace=True)
df_close = df_temp['Close']

loc = df_close.index.get_loc('2015-08-17')

在这两种情况下,df_close 都是一个系列,并且其中包含日期。唯一的区别是,在正确的场景中,它包含格式为的日期,例如 2013-03-25 00:00:00

而在不正确的格式中,它的格式类似于 2014-01-01

这是日志。

runfile('C:/Users/Arun/.spyder-py3/Practise 文件/market_correction.py', wdir='C:/Users/Arun/.spyder-py3/Practise files') Traceback(最近一次调用最后一次):

文件“”,第 1 行,在 runfile('C:/Users/Arun/.spyder-py3/Practise 文件/market_correction.py', wdir='C:/Users/Arun/.spyder-py3/Practise 文件')

文件 "C:\Users\Arun\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", 第 705 行,在运行文件中 execfile(文件名,命名空间)

文件 "C:\Users\Arun\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", 第 102 行,在 execfile 中 exec(编译(f.read(),文件名,'exec'),命名空间)

文件“C:/Users/Arun/.spyder-py3/Practise 文件/market_correction.py”,第 27 行,在 loc = df_close.index.get_loc('2015-08-17')

文件 "C:\Users\Arun\Anaconda3\lib\site-packages\pandas\core\indexes\base.py", 第 2527 行,在 get_loc 中 return self._engine.get_loc(self._maybe_cast_indexer(key))

文件“pandas/_libs/index.pyx”,第 117 行,在 pandas._libs.index.IndexEngine.get_loc

文件“pandas/_libs/index.pyx”,第 139 行,在 pandas._libs.index.IndexEngine.get_loc

文件“pandas/_libs/hashtable_class_helper.pxi”,第 1265 行,在 pandas._libs.hashtable.PyObjectHashTable.get_item

文件“pandas/_libs/hashtable_class_helper.pxi”,第 1273 行,在 pandas._libs.hashtable.PyObjectHashTable.get_item

KeyError: '2015-08-17'

我做错了什么?这一天出现在系列中。

我也尝试过 df.loc 方法,但这会产生其他错误。

我在 python 3.6 中使用 anaconda spyder

解决方案:

import pandas as pd
#import numpy as np
import matplotlib.pyplot as plt
from IPython import get_ipython
from datetime import date
from nsepy import get_history

get_ipython().run_line_magic('matplotlib', 'inline')

sym = 'SBIN'
df_close = pd.DataFrame()
df_temp = get_history(symbol=sym,
                   start=date(2014,1,1),
                   end=date(2018,3,24))

**df_temp.reset_index(drop = False, inplace = True)
df_temp['Date']= pd.to_datetime(df_temp['Date'])
df_temp.set_index('Date',inplace=True)**
df_close = df_temp['Close']

loc = df_close.index.get_loc('2015-08-17')

【问题讨论】:

  • 如果在第二个代码中取消注释 df_temp.set_index('date',inplace=True) 它工作吗?
  • 它给出了“日期”的密钥错误。在删除索引然后重新索引它之后工作。谢谢

标签: python pandas nsepy


【解决方案1】:

我认为需要set_index 并且可能转换为日期时间,因为KeyError 意味着索引中没有2015-08-17 的值:

#check if DatetimeIndex
print (df_temp.index)

#if necessary convert column to index
df_temp.set_index('date',inplace=True) 
#if necessary convert to datetimes
df_temp.index= pd.to_datetime(df_temp.index)

loc = df_temp.index.get_loc('2015-08-17')

【讨论】:

  • 谢谢。有效。我不得不删除索引然后重新索引它。 df_temp = get_history(symbol=sym, start=date(2014,1,1), end=date(2018,3,24)) df_temp.reset_index(drop = False, inplace = True) df_temp['Date']= pd .to_datetime(df_temp['Date']) df_temp.set_index('Date',inplace=True) df_close = df_temp['Close'] loc = df_close.index.get_loc('2015-08-17')
  • @ArunKamath - 我检查了你的代码,也许 df_temp.reset_index(drop = False, inplace = True) 也应该省略。
猜你喜欢
  • 2020-05-08
  • 2018-06-25
  • 2020-12-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-27
  • 2016-12-07
相关资源
最近更新 更多