Python 获取数据帧中的最后一个值时出现KeyError

Python 获取数据帧中的最后一个值时出现KeyError,python,pandas,dataframe,Python,Pandas,Dataframe,下面代码中的数据框可以调用任何值,例如q\u data.low[0],q\u data.date[8],但不能从最后一个调用,如q\u data.low[-1] url = 'https://api.iextrading.com/1.0/stock/AAPL/chart/1y' q_data = pd.read_json(url) data = q_data.date[0] data1 = q_data.date[-1] Traceback (most recent call last):

下面代码中的数据框可以调用任何值,例如
q\u data.low[0],q\u data.date[8]
,但不能从最后一个调用,如
q\u data.low[-1]

url = 'https://api.iextrading.com/1.0/stock/AAPL/chart/1y'
q_data = pd.read_json(url)
data =  q_data.date[0]
data1 = q_data.date[-1]

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/vinus/.local/lib/python2.7/site-packages/pandas/core/series.py", line 601, in __getitem__
    result = self.index.get_value(self, key)
  File "/home/vinus/.local/lib/python2.7/site-packages/pandas/core/indexes/base.py", line 2477, in get_value
    tz=getattr(series.dtype, 'tz', None))
  File "pandas/_libs/index.pyx", line 98, in pandas._libs.index.IndexEngine.get_value (pandas/_libs/index.c:4
404)
  File "pandas/_libs/index.pyx", line 106, in pandas._libs.index.IndexEngine.get_value (pandas/_libs/index.c:
4087)
  File "pandas/_libs/index.pyx", line 154, in pandas._libs.index.IndexEngine.get_loc (pandas/_libs/index.c:51
26)
  File "pandas/_libs/hashtable_class_helper.pxi", line 759, in pandas._libs.hashtable.Int64HashTable.get_item
 (pandas/_libs/hashtable.c:14031)
  File "pandas/_libs/hashtable_class_helper.pxi", line 765, in pandas._libs.hashtable.Int64HashTable.get_item
 (pandas/_libs/hashtable.c:13975)
KeyError: -1 
url='1〕https://api.iextrading.com/1.0/stock/AAPL/chart/1y'
q_data=pd.read_json(url)
数据=q_数据。日期[0]
数据1=q_数据。日期[-1]
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
文件“/home/vinus/.local/lib/python2.7/site-packages/pandas/core/series.py”,第601行,在__
结果=self.index.get_值(self,key)
get_值中的文件“/home/vinus/.local/lib/python2.7/site packages/pandas/core/index/base.py”,第2477行
tz=getattr(series.dtype,'tz',无))
文件“pandas/_libs/index.pyx”,第98行,在pandas._libs.index.IndexEngine.get_值中(pandas/_libs/index.c:4
404)
文件“pandas/_libs/index.pyx”,第106行,在pandas._libs.index.IndexEngine.get_值中(pandas/_libs/index.c:
4087)
文件“pandas/_libs/index.pyx”,第154行,在pandas._libs.index.IndexEngine.get_loc(pandas/_libs/index.c:51)中
26)
文件“pandas/_libs/hashtable_class_helper.pxi”,第759行,在pandas._libs.hashtable.Int64HashTable.get_项中
(pandas/_libs/hashtable.c:14031)
文件“pandas/_libs/hashtable_class_helper.pxi”,第765行,在pandas._libs.hashtable.Int64HashTable.get_项中
(pandas/_libs/hashtable.c:13975)
键错误:-1
代码有什么问题?如何获取数据帧中的最后一个值?

我认为需要,因为
日期[-1]
查找不存在的
-1
索引,因此引发错误:

data1 =  q_data.date.iloc[-1]
print (data1)
2018-05-11 00:00:00
另一种解决方案,包含和用于
日期
列的位置:

data1 = q_data.iloc[-1, q_data.columns.get_loc('date')]
print (data1)
2018-05-11 00:00:00
q\u数据。日期[len(q\u数据)-1]