如何解决仅当某个列存在时,如何访问数据框值?
如果数据框中没有“Short Long Term Debt”一词,我该如何设置,然后使用 short_long_term_debt = 0
,但如果有,则使用最后一行?
import pandas_datareader.data as web
import pandas as pd
import datetime
import requests
pd.set_option('display.max_rows',500)
pd.set_option('display.max_columns',500)
pd.set_option('display.width',150)
ticker = yf.Ticker("ATVI")
financials = ticker.financials.T
balance = ticker.balance_sheet.T
interest_expense = financials['Interest Expense']['2020'].iloc[0]
if not balance['Short Long Term Debt']:
short_long_term_debt = 0
short_long_term_debt = balance['Short Long Term Debt']['2020'].iloc[0]
目前此代码给出以下错误:
KeyError Traceback (most recent call last)
/usr/local/lib/python3.7/dist-packages/pandas/core/indexes/base.py in get_loc(self,key,method,tolerance)
2897 try:
-> 2898 return self._engine.get_loc(casted_key)
2899 except KeyError as err:
pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()
pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()
pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()
pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()
KeyError: 'Short Long Term Debt'
The above exception was the direct cause of the following exception:
KeyError Traceback (most recent call last)
2 frames
/usr/local/lib/python3.7/dist-packages/pandas/core/indexes/base.py in get_loc(self,tolerance)
2898 return self._engine.get_loc(casted_key)
2899 except KeyError as err:
-> 2900 raise KeyError(key) from err
2901
2902 if tolerance is not None:
KeyError: 'Short Long Term Debt'
解决方法
您可以检查 Short Long Term Debt
是否在 balance.columns
中:
if 'Short Long Term Debt' in balance.columns:
short_long_term_debt = balance['Short Long Term Debt']['2020'].iloc[0]
else:
short_long_term_debt = 0
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。