如何修复Python 3.7中的'KeyError:**** _ target'错误

时间:2019-03-22 21:41:36

标签: python python-3.x pandas numpy

我从youtube获得了此代码,

不确定,为什么家庭教师(Sentdex)没有得到与我相同的错误。 我有一个日期为索引的Test.csv文件

Dates 'A Close' 'B Close' 'DLF Close' 'ICICI Close'
1 jan 18  555     111        122         400
2 jan 18  566     132        128         398

以此类推.....

from collections import Counter
import numpy as np
import pandas as pd

hm_days = 7

def process_data(ticker):
    df = pd.read_csv('Test.csv', index_col=0)
    tickers = df.columns.values.tolist()
    df.fillna(0, inplace=True)
    for i in range(1, hm_days+1):
        df['{}_{}d'.format(ticker, i)] = (df[ticker].shift(-i)- 
                                      df[ticker])/df[ticker]
    df.fillna(0, inplace=True)

    return tickers, df

def buy_sell_hold(*args):
    cols = [c for c in args]
    req = 0.02
    for col in cols:
        if all(col) > req:
            return 1
        if all(col) < -req:
            return -1
    return 0

def extract_feature(ticker):
    tickers, df = process_data(ticker)
    df['{}_target'.format(ticker)] = list(map(buy_sell_hold, 
                                df[['{}_{}d'.format(ticker, i)
                                for i in range(1, hm_days + 1)]].values))
    vals = df['{}_target'.format(ticker)].values.tolist()
    str_vals = [str(i) for i in vals]
    print('Data spread:', Counter(str_vals))
    df.fillna(0, inplace=True)
    df = df.replace([np.inf, -np.inf], np.nan)
    df.dropna(inplace=True)
    df_vals = df[[ticker for ticker in tickers]].pct_change()
    df_vals = df_vals.replace([np.inf, -np.inf], 0)
    df_vals.fillna(0, inplace=True)
    x = df_vals.values
    y = df['{}_target'.format(ticker)].values

    return x, y, df

extract_feature('DLF Close')

这是我得到的错误:

Traceback (most recent call last):
  File "C:\Users\Sudipto\Anaconda3\lib\site-packages\pandas\core\indexes\base.py", line 3078, in get_loc
    return self._engine.get_loc(key)
  File "pandas\_libs\index.pyx", line 140, in pandas._libs.index.IndexEngine.get_loc
  File "pandas\_libs\index.pyx", line 162, in pandas._libs.index.IndexEngine.get_loc
  File "pandas\_libs\hashtable_class_helper.pxi", line 1492, in pandas._libs.hashtable.PyObjectHashTable.get_item
  File "pandas\_libs\hashtable_class_helper.pxi", line 1500, in pandas._libs.hashtable.PyObjectHashTable.get_item
KeyError: 'DLF Close_target'

在处理上述异常期间,发生了另一个异常:

Traceback (most recent call last):
  File "C:\Users\Sudipto\Dropbox\Sentdex\PPF Backup\try.py", line 48, in <module>
    extract_feature('DLF Close')
  File "C:\Users\Sudipto\Dropbox\Sentdex\PPF Backup\try.py", line 33, in extract_feature
    vals = df['{}_target'.format(ticker)].values.tolist()
  File "C:\Users\Sudipto\Anaconda3\lib\site-packages\pandas\core\frame.py", line 2688, in __getitem__
    return self._getitem_column(key)
  File "C:\Users\Sudipto\Anaconda3\lib\site-packages\pandas\core\frame.py", line 2695, in _getitem_column
    return self._get_item_cache(key)
  File "C:\Users\Sudipto\Anaconda3\lib\site-packages\pandas\core\generic.py", line 2489, in _get_item_cache
    values = self._data.get(item)
  File "C:\Users\Sudipto\Anaconda3\lib\site-packages\pandas\core\internals.py", line 4115, in get
    loc = self.items.get_loc(item)
  File "C:\Users\Sudipto\Anaconda3\lib\site-packages\pandas\core\indexes\base.py", line 3080, in get_loc
    return self._engine.get_loc(self._maybe_cast_indexer(key))
  File "pandas\_libs\index.pyx", line 140, in pandas._libs.index.IndexEngine.get_loc
  File "pandas\_libs\index.pyx", line 162, in pandas._libs.index.IndexEngine.get_loc
  File "pandas\_libs\hashtable_class_helper.pxi", line 1492, in pandas._libs.hashtable.PyObjectHashTable.get_item
  File "pandas\_libs\hashtable_class_helper.pxi", line 1500, in pandas._libs.hashtable.PyObjectHashTable.get_item
KeyError: 'DLF Close_target'

我用一行来收集问题:

vals = df['{}_target'.format(ticker)].values.tolist()

我检查了两次代码,三次。。。当我要求“ DLF关闭”时,我无法弄清楚出了什么问题。有人可以帮我吗?

0 个答案:

没有答案