如何从YahooQuery返回的Python字典提取特定字段转DataFrame?
从YahooQuery的earnings_trend中提取特定growth字段并转为DataFrame
完整解决方案代码
import pandas as pd from yahooquery import Ticker # 获取AAPL的收益趋势数据 aapl = Ticker('AAPL') earnings_trend = aapl.earnings_trend # 提取trend列表数据 trend_items = earnings_trend['AAPL']['trend'] # 提取所有包含growth字段的条目,保留时期和增长率 filtered_data = [] for item in trend_items: if 'growth' in item and item['growth'] is not None: filtered_data.append({ 'period': item['period'], 'growth': item['growth'] }) # 转换为DataFrame growth_df = pd.DataFrame(filtered_data) print(growth_df)
提取特定时期的growth(比如示例中的'-5y')
如果只需要某一个特定时期的增长率,可以直接定位:
# 获取'-5y'时期的growth值 target_growth = None for item in trend_items: if item.get('period') == '-5y' and 'growth' in item: target_growth = item['growth'] break # 转为DataFrame target_df = pd.DataFrame({'period': ['-5y'], 'growth': [target_growth]}) print(target_df)
代码说明
- 原始数据是嵌套字典结构,需要先进入
['AAPL']['trend']拿到包含各时期数据的列表 - 遍历列表时,过滤掉没有
growth字段或growth为空的条目,避免无效数据 - 用字典整理需要的字段(时期和增长率),再通过
pd.DataFrame转换为表格格式
内容的提问来源于stack exchange,提问作者HTMLHelpMe
相关产品推荐
相关产品推荐

