[英]How do I add data to a column only if a certain value exists in previous column using Python and Faker?
[英]How do I access a dataframe value only if a certain column exists?
我该如何做到这一点,如果 dataframe 中没有“短期长期债务”一词,那么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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.