如何提取模块函数返回的指定字段?以yahoo_fin的get_data函数为例
实现方法说明
首先你现有代码存在变量顺序错误:today 变量的定义需要放在调用get_data函数之前,否则会触发变量未定义的报错。
yahoo_fin的get_data接口返回的是Pandas的DataFrame格式对象,提取high列有两种常用写法:
- 写法1(兼容性最高,推荐):直接用中括号取列名,不需要加括号
如果你需要的是带索引的Series格式的high列数据:today_high = today_data['high']
如果你只需要当日最高价的单独数值:today_high = today_data['high'].iloc[0] - 写法2(和你猜测的逻辑接近,注意不要加括号):high是DataFrame的属性不是可调用方法,不需要加括号
取Series格式:today_high = today_data.high
取单独数值:today_high = today_data.high.iloc[0]
修正后可直接运行的完整代码
from yahoo_fin.stock_info import * import datetime # 先定义today变量再调用get_data today = datetime.date.today() print(today) today_data = get_data("ADA-CAD", start_date = today) # 提取当日最高价数值 today_high = today_data['high'].iloc[0] print("当日最高价为:", today_high)
内容的提问来源于stack exchange,提问作者Timothy Shal
相关产品推荐
相关产品推荐

