2017-03-31 41 views
1

我想设置Python(3.4)代码按日期排序时间序列。Python 3.4熊猫根据日期排序市场数据

在Python Shell,我在下面的

>>>data = quandl.get("YAHOO/INDEX_GSPC", start_date="2017-01-01", end_date="2017-01-20") 
>>>print(data) 

左右键,我可以在数据加载。但是,当我尝试使用命令排序

>>>data = data.sort_values(by='Date') 

我收到以下错误消息列表。我似乎无法理解/得到日期排序的语法从http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.sort_values.html

专家在那里.......,非常感谢您的建议。


Traceback (most recent call last): 
    File "C:\Python34\lib\site-packages\pandas\indexes\base.py", line 2134, in get_loc 
    return self._engine.get_loc(key) 
    File "pandas\index.pyx", line 132, in pandas.index.IndexEngine.get_loc (pandas\index.c:4433) 
    File "pandas\index.pyx", line 154, in pandas.index.IndexEngine.get_loc (pandas\index.c:4279) 
    File "pandas\src\hashtable_class_helper.pxi", line 732, in pandas.hashtable.PyObjectHashTable.get_item (pandas\hashtable.c:13742) 
    File "pandas\src\hashtable_class_helper.pxi", line 740, in pandas.hashtable.PyObjectHashTable.get_item (pandas\hashtable.c:13696) 
KeyError: 'Date' 

During handling of the above exception, another exception occurred: 

Traceback (most recent call last): 
    File "<pyshell#37>", line 1, in <module> 
    data = data.sort_values(by='Date') 
    File "C:\Python34\lib\site-packages\pandas\core\frame.py", line 3230, in sort_values 
    k = self.xs(by, axis=other_axis).values 
    File "C:\Python34\lib\site-packages\pandas\core\generic.py", line 1770, in xs 
    return self[key] 
    File "C:\Python34\lib\site-packages\pandas\core\frame.py", line 2059, in __getitem__ 
    return self._getitem_column(key) 
    File "C:\Python34\lib\site-packages\pandas\core\frame.py", line 2066, in _getitem_column 
    return self._get_item_cache(key) 
    File "C:\Python34\lib\site-packages\pandas\core\generic.py", line 1386, in _get_item_cache 
    values = self._data.get(item) 
    File "C:\Python34\lib\site-packages\pandas\core\internals.py", line 3543, in get 
    loc = self.items.get_loc(item) 
    File "C:\Python34\lib\site-packages\pandas\indexes\base.py", line 2136, in get_loc 
    return self._engine.get_loc(self._maybe_cast_indexer(key)) 
    File "pandas\index.pyx", line 132, in pandas.index.IndexEngine.get_loc (pandas\index.c:4433) 
    File "pandas\index.pyx", line 154, in pandas.index.IndexEngine.get_loc (pandas\index.c:4279) 
    File "pandas\src\hashtable_class_helper.pxi", line 732, in pandas.hashtable.PyObjectHashTable.get_item (pandas\hashtable.c:13742) 
    File "pandas\src\hashtable_class_helper.pxi", line 740, in pandas.hashtable.PyObjectHashTable.get_item (pandas\hashtable.c:13696) 
KeyError: 'Date' 

回答

0

确保你看看错误。您正在获得KeyError,这意味着您的DataFrame中不存在列Date。这就像日期存储在需要sort_index方法的索引中。您在DataFrame中看到的'Date'名称是索引的名称,而不是列。

data.sort_index() 
1

quandl.get加载与日期指数DataFrame

所以,如果你按索引,你是好去:

data = data.sort_index() 
+1

感谢,现在它工作。我使用data = data.sort_index(Ascending = False),我可以得到它显示数据,按日期显示,最近显示在顶部。 – Kiann