def update_data(n, val): # inpur parameter(s)
if n == None:
return "Hey there! Please enter a legitimate stock code to get details.", "https://melmagazine.com/wp-content/uploads/2019/07/Screen-Shot-2019-07-31-at-5.47.12-PM.png", "Stonks", None, None, None
# raise PreventUpdate
else:
if val == None:
raise PreventUpdate
else:
ticker = yf.Ticker(val)
inf = ticker.info
df = pd.DataFrame().from_dict(inf, orient="index").T
df[["logo_url", "shortName", "longBusinessSummary"]]
return df['logo_url'].values[0], df['shortName'].values[
0], df['longBusinessSummary'].values[0], None, None, None
在此代码中我收到错误...
Traceback (most recent call last):
File "C:\Users\SK\Desktop\stock-dash\app.py", line 122, in update_data
df[["logo_url", "shortName", "longBusinessSummary"]]
File "C:\Users\SK\Desktop\stock-dash\Project\lib\site-packages\pandas\core\frame.py", line 3767, in __getitem__
indexer = self.columns._get_indexer_strict(key, "columns")[1]
File "C:\Users\SK\Desktop\stock-dash\Project\lib\site-packages\pandas\core\indexes\base.py", line 5876, in _get_indexer_strict
self._raise_if_missing(keyarr, indexer, axis_name)
File "C:\Users\SK\Desktop\stock-dash\Project\lib\site-packages\pandas\core\indexes\base.py", line 5938, in _raise_if_missing
raise KeyError(f"{not_found} not in index")
KeyError: "['logo_url'] not in index"
我想要它的解决方案,请帮助我
最佳答案
行 df[["logo_url", "shortName", "longBusinessSummary"]]
似乎旨在从 DataFrame 中选择特定列,但缺少用于存储的赋值语句选定的列。
要修复该错误,您需要将选定的列重新分配给 df 变量。这是更正后的代码:
def update_data(n, val):
if n is None:
return (
"Hey there! Please enter a legitimate stock code to get details.",
"https://melmagazine.com/wp-content/uploads/2019/07/Screen-Shot-2019-07-31-at-5.47.12-PM.png",
"Stonks",
None,
None,
None,
)
else:
if val is None:
raise PreventUpdate
else:
ticker = yf.Ticker(val)
inf = ticker.info
df = pd.DataFrame().from_dict(inf, orient="index").T
df = df[["logo_url", "shortName", "longBusinessSummary"]] # Assign selected columns back to df
return (
df['logo_url'].values[0],
df['shortName'].values[0],
df['longBusinessSummary'].values[0],
None,
None,
None,
)
关于python-3.x - 我的 python 代码中有一个错误 key 错误 ['logo_url' ] 不在索引中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76345304/