【发布时间】:2020-12-06 23:32:23
【问题描述】:
尝试从 df['Close'] 列中的 yfinance 计算一些变量。 但是我得到了这个我以前从未见过的错误。这是代码:
import os
import pandas as pd
import plotly.graph_objects as go
symbols = 'AAPL'
for filename in os.listdir('datasets/'):
#print(filename)
symbol = filename.split('.')[0]
#print(symbol)
df = pd.read_csv('datasets/{}'.format(filename))
if df.empty:
continue
df['20_sma'] = df['Close'].rolling(window=20).mean()
df['stddev'] = df['Close'].rolling(window=20).std()
df['lowerband'] = df['20_sma'] + (2* df['stddev'])
df['upperband'] = df['20_sma'] - (2* df['stddev'])
if symbol in symbols:
print(df)
这是错误信息:
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/pandas/core/indexes/base.py", line 2895, in get_loc
return self._engine.get_loc(casted_key)
File "pandas/_libs/index.pyx", line 70, in pandas._libs.index.IndexEngine.get_loc
File "pandas/_libs/index.pyx", line 101, in pandas._libs.index.IndexEngine.get_loc
File "pandas/_libs/hashtable_class_helper.pxi", line 1675, in pandas._libs.hashtable.PyObjectHashTable.get_item
File "pandas/_libs/hashtable_class_helper.pxi", line 1683, in pandas._libs.hashtable.PyObjectHashTable.get_item
KeyError: 'Close'
上述异常是以下异常的直接原因:
Traceback (most recent call last):
File "/Users/Kit/Documents/TTM_squeezer/squeeze.py", line 16, in <module>
df['20_sma'] = df['Close'].rolling(window=20).mean()
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/pandas/core/frame.py", line 2906, in __getitem__
indexer = self.columns.get_loc(key)
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/pandas/core/indexes/base.py", line 2897, in get_loc
raise KeyError(key) from err
KeyError: 'Close'
似乎“关闭”列导致了这个错误,但我不知道为什么? 非常感谢
【问题讨论】:
-
df中是否存在`'Close'` 列? (注意我没有问你是否期望它存在!请通过调试检查它是否确实存在于代码中) -
嗨,杰夫,它确实存在于 csv 文件中
-
注意我没有问你是否期望它存在!请通过调试检查它是否确实存在于代码中!
-
很抱歉 Jeff 没有真正关注,请您再解释一下吗?
-
我使用yfinance直接在线检索了数据,并且数据被成功检索,没有出现任何错误。 cmets中提到的,好像是本地文件导致的,所以请检查是否有列,区分大小写等。
标签: python pandas dataframe yfinance