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

finvizfinance与Pandas导出股票数据至Excel遇格式异常求助

问题描述

使用Python的finvizfinance库获取股票基本面数据时,创建Pandas DataFrame出现空表问题:

  • 打印stock_fundament能得到正常字典(如{'Company': 'Tesla, Inc.', 'Sector': 'Consumer Cyclical', ...})
  • 设置index=0并指定自定义columns后,生成的DataFrame显示为空:

    Empty DataFrame
    Columns: [a, b, c, d, e, f, g, h, i, j]
    Index: []

  • 无法正常将数据导出到Excel,询问是否需要将索引设置为finvizfinance返回的字段列表。
解决方案

问题根源

你创建DataFrame的方式错误:stock_fundament是单条记录的字典,但你手动指定了和字典键完全无关的columns=['a'...'j'],导致Pandas找不到匹配的数据,因此生成空表。不需要把字段列表设为索引,正确的做法是让字典的键作为DataFrame的列名。

修正步骤

  1. 正确创建DataFrame:
    • 推荐方式:将字典放入列表中,直接转成单行DataFrame(符合常规表格结构)
    • 可选方式:如果希望字段作为行标签,使用from_dict并指定orient='index'
  2. 导出Excel:确保DataFrame有数据后,直接执行导出逻辑即可。

修正后的完整代码

from finvizfinance.quote import finvizfinance
import pandas as pd

stock = finvizfinance('tsla')
stock_fundament = stock.ticker_fundament()

# 推荐:生成常规的单行DataFrame(字段为列名)
df = pd.DataFrame([stock_fundament])

# 可选:将字段作为行标签,值作为列(适合单条数据竖排查看)
# df = pd.DataFrame.from_dict(stock_fundament, orient='index', columns=['Value'])

print(stock_fundament)
print(df)

# 导出到Excel,index=False可去掉默认索引列,让表格更整洁
writer = pd.ExcelWriter(r'C:\Users\ncwes\AppData\Local\Programs\Python\Python310\pandas_simple.xlsx')
df.to_excel(writer, sheet_name='Sheet1', index=False)
writer.close()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 07:23:38