KeyError:“标签[-2]不在[index]中”

时间:2019-04-26 10:42:43

标签: python python-3.x pandas

在第10到13行上打印时,

将数据帧索引为df ['column_name']。iloc [-1],并在该位置打印值。

但是当我在条件块中使用相同的语法时,它将引发错误。

我在做什么错了?

import pandas

def job():
        # get the dataframe
        df = pandas.read_csv('stock_prices.csv')

        # change dataframe column types datatypes
        df = df.astype({'close': 'float64', 'high': 'float64', 'low': 'float64', 'open': 'float64', 'timestamp': 'int64', 'volume': 'int64'})

        print('last close price :', df['close'].iloc[-1])
        print('2nd last close price :', df['close'].iloc[-2])
        print('last open price :', df['open'].iloc[-1])
        print('2nd last open price :', df['open'].iloc[-2])


        if df['open'].iloc[-2] < df['open'].iloc[-1]:
            if df['close'].iloc[-2] < df['close'].iloc[-2]:
                print('its time to buy')
                return


        if df['open'].loc[-2] > df['open'].loc[-1]:
            if df['close'].loc[-2] > df['close'].iloc[-1]:
                print('its time to sell')
                return

if __name__ == '__main__':
    job()

输出如下

last close price : 588.5
2nd last close price : 587.3
last open price : 587.25
2nd last open price : 586.5
Traceback (most recent call last):
  File "C:\Users\Whistler.81\AppData\Local\Programs\Python\Python36\lib\site-packages\pandas\core\indexing.py", line 1506, in _has_valid_type
    error()
  File "C:\Users\Whistler.81\AppData\Local\Programs\Python\Python36\lib\site-packages\pandas\core\indexing.py", line 1501, in error
    axis=self.obj._get_axis_name(axis)))
KeyError: 'the label [-2] is not in the [index]'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\Whistler.81\Desktop\for_stack.py", line 28, in <module>
    job()
  File "C:\Users\Whistler.81\Desktop\for_stack.py", line 22, in job
    if df['open'].loc[-2] > df['open'].loc[-1]:
  File "C:\Users\Whistler.81\AppData\Local\Programs\Python\Python36\lib\site-packages\pandas\core\indexing.py", line 1373, in __getitem__
    return self._getitem_axis(maybe_callable, axis=axis)
  File "C:\Users\Whistler.81\AppData\Local\Programs\Python\Python36\lib\site-packages\pandas\core\indexing.py", line 1626, in _getitem_axis
    self._has_valid_type(key, axis)
  File "C:\Users\Whistler.81\AppData\Local\Programs\Python\Python36\lib\site-packages\pandas\core\indexing.py", line 1514, in _has_valid_type
    error()
  File "C:\Users\Whistler.81\AppData\Local\Programs\Python\Python36\lib\site-packages\pandas\core\indexing.py", line 1501, in error
    axis=self.obj._get_axis_name(axis)))
KeyError: 'the label [-2] is not in the [index]'
[Finished in 1.9s]

0 个答案:

没有答案