You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从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)

代码说明

  1. 原始数据是嵌套字典结构,需要先进入['AAPL']['trend']拿到包含各时期数据的列表
  2. 遍历列表时,过滤掉没有growth字段或growth为空的条目,避免无效数据
  3. 用字典整理需要的字段(时期和增长率),再通过pd.DataFrame转换为表格格式

内容的提问来源于stack exchange,提问作者HTMLHelpMe

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 22:28:41