仅当特定列存在时如何访问数据框值?

How do I access a dataframe value only if a certain column exists?

如何做到如果数据框中没有术语 '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, key, method, 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