Search code examples
pythonpandasdataframecontainsyfinance

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


How do I make it so that if there is no term 'Short Long Term Debt' in the dataframe then short_long_term_debt = 0, but if there is then use the final line?

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]

Currently this code gives the following error:

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'

Solution

  • You can check if Short Long Term Debt is in 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