来自Pandas的关键错误

时间:2014-12-26 11:58:06

标签: python pandas

我在python中有以下代码。

 d1=pd.read_excel("data1.xlsx",sheetname=0, index_col = "Time", parse_date=True)
 d1=d1.sort_index()
 for val in d1.columns:
      start_his=d1[str(val)]

data1.xlsx包含

Time        Start   High    Low     End     5
05/12/2014  28,000  31,500  27,400  29,900  29,740.00
28/11/2014  29,450  29,450  27,950  28,250  30,190.00
21/11/2014  30,500  30,500  28,100  29,300  30,840.00
14/11/2014  31,750  31,750  29,600  29,900  31,200.00
07/11/2014  32,250  32,750  30,500  31,350  31,620.00
31/10/2014  31,800  33,000  31,300  32,150  32,230.00
24/10/2014  31,300  32,750  30,800  31,500  32,680.00
17/10/2014  32,000  32,150  30,550  31,100  33,270.00
10/10/2014  34,550  34,550  32,000  32,000  33,920.00
02/10/2014  35,000  35,000  32,400  34,400  34,560.00
26/09/2014  34,600  35,000  33,600  34,400  34,770.00
19/09/2014  34,350  34,750  32,200  34,450  35,070.00

我得到前4列的输出(开始,高,低和结束),但第5列显示关键错误。如果我更改数字' 5'任何其他值(即Alpha数字)它正常工作,但它不接受列标题中的数字。请帮忙解决这个错误。

我得到的错误是

Traceback (most recent call last):
  File "ARIMA & Byesian.py", line 94, in <module>
    start_his=d1[str(val)]
  File "/usr/local/lib/python2.7/dist-packages/pandas/core/frame.py", line 1780, in __getitem__
    return self._getitem_column(key)
  File "/usr/local/lib/python2.7/dist-packages/pandas/core/frame.py", line 1787, in _getitem_column
    return self._get_item_cache(key)
  File "/usr/local/lib/python2.7/dist-packages/pandas/core/generic.py", line 1068, in _get_item_cache
    values = self._data.get(item)
  File "/usr/local/lib/python2.7/dist-packages/pandas/core/internals.py", line 2849, in get
    loc = self.items.get_loc(item)
  File "/usr/local/lib/python2.7/dist-packages/pandas/core/index.py", line 1402, in get_loc
    return self._engine.get_loc(_values_from_object(key))
  File "pandas/index.pyx", line 134, in pandas.index.IndexEngine.get_loc (pandas/index.c:3812)
  File "pandas/index.pyx", line 154, in pandas.index.IndexEngine.get_loc (pandas/index.c:3692)
  File "pandas/hashtable.pyx", line 696, in pandas.hashtable.PyObjectHashTable.get_item (pandas/hashtable.c:12299)
  File "pandas/hashtable.pyx", line 704, in pandas.hashtable.PyObjectHashTable.get_item (pandas/hashtable.c:12250)
KeyError: '5'

1 个答案:

答案 0 :(得分:3)

您正在使用str(val)5将成为'5'。直接使用val,如下所示:

d1=pd.read_excel("data1.xlsx",sheetname=0, index_col = "Time", parse_date=True)
d1=d1.sort_index()
for val in d1.columns:
   start_his=d1[val]