如何在yfinance获取Yahoo Finance数据时用N/A替代缺失字段报错?
解决yfinance获取数据时KeyError的问题
直接通过字典索引(comp.info['key'])访问不存在的键会触发KeyError,要实现缺失数据返回N/A且不中断程序,改用字典的get()方法即可——该方法允许指定键不存在时的默认返回值。
修改后的代码如下:
import yfinance as yf import pandas comp = yf.Ticker("ERO") # 用get方法获取字段,缺失时返回N/A industry = comp.info.get('industry', 'N/A') sector = comp.info.get('sector', 'N/A') current_price = comp.info.get('currentPrice', 'N/A') target_mean_price = comp.info.get('targetMeanPrice', 'N/A') print(industry, sector, current_price, target_mean_price)
这样无论targetMeanPrice或其他字段是否存在,程序都会正常输出:存在的字段返回对应数据,缺失的字段返回N/A,不会触发报错。
内容的提问来源于stack exchange,提问作者k07
相关产品推荐
相关产品推荐

