以下代码中的pandas数据框可以调用任何值,例如q_data.low[0],q_data.date[8]
,但不能像q_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
代码有什么问题?如何获取数据框中的最后一个值?
答案 0 :(得分:3)
我认为需要Series.iloc
因为date[-1]
正在查找不存在-1
的索引,所以会引发错误:
data1 = q_data.date.iloc[-1]
print (data1)
2018-05-11 00:00:00
使用DataFrame.iloc
和get_loc
作为date
列位置的另一种解决方案:
data1 = q_data.iloc[-1, q_data.columns.get_loc('date')]
print (data1)
2018-05-11 00:00:00