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

如何解决YahooQuery字典类型模块导出CSV时的AttributeError错误?

解决AttributeError: 'dict' object has no attribute 'to_csv'错误

你运行代码时触发的AttributeError,核心原因很明确:faang.asset_profile返回的是**字典(dict)**类型,而to_csv()是pandas DataFrame独有的方法,字典本身没有这个属性。

错误代码示例:

import pandas as pd
from yahooquery import Ticker
symbols = ['AAPL','GOOG','MSFT'] 
faang = Ticker(symbols)
faang.asset_profile
df = (faang.asset_profile)
df.to_csv('output.csv', mode='a', index=True, header=True)

YahooQuery里不少属性(比如asset_profile)都返回字典结构,而像valuation_measures这类属性会直接返回pandas DataFrame,所以替换后能正常调用to_csv()。

解决方法

把字典转换成pandas DataFrame后再保存,根据字典结构选对应方式:

  • 若字典是按股票代码分组的嵌套结构(比如AAPL、GOOG各自对应一组资产配置数据),用from_dict并指定orient='index':
import pandas as pd
from yahooquery import Ticker
symbols = ['AAPL','GOOG','MSFT'] 
faang = Ticker(symbols)
# 获取字典数据
asset_profile_dict = faang.asset_profile
# 转换为DataFrame,orient='index'将股票代码作为行索引
df = pd.DataFrame.from_dict(asset_profile_dict, orient='index')
# 保存为CSV
df.to_csv('output.csv', mode='a', index=True, header=True)
  • 若字典是单层键值对结构,直接用pd.DataFrame([asset_profile_dict])转换即可。

如果不确定返回类型,先执行print(type(faang.asset_profile))确认,只要是dict就转成DataFrame再操作。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 06:10:24