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

如何将嵌套字典转换为Pandas DataFrame处理股票数据

问题

爬取得到的股票数据以嵌套字典形式存储,直接执行data_2 = pd.DataFrame(Data)转换为Pandas DataFrame时,结果结构混乱不符合预期,需要将嵌套字典转换为结构规整的DataFrame。

解决方案

根据嵌套字典的层级结构,可采用以下两种针对性方法:

1. 单层嵌套字典(键为股票标识,值为字段字典)

如果你的数据是类似下面的单层嵌套结构:

# 示例数据
stock_data = {
    '000001': {'name': '平安银行', 'price': 10.5, 'volume': 25000000},
    '000002': {'name': '万科A', 'price': 12.3, 'volume': 18000000}
}

直接用pd.DataFrame()会把股票代码作为列名、字段作为行索引,结构完全倒置。此时可以用from_dict指定orient='index'来快速调整:

import pandas as pd

# 转换并重置索引
df = pd.DataFrame.from_dict(stock_data, orient='index').reset_index()
# 重命名索引列为股票代码
df.rename(columns={'index': 'stock_code'}, inplace=True)

转换后得到的规整DataFrame结构:

stock_codenamepricevolume
000001平安银行10.525000000
000002万科A12.318000000

2. 多层嵌套字典(字段包含子字典)

如果数据存在更深层级的嵌套,比如:

# 多层嵌套示例数据
stock_data_deep = {
    '000001': {
        'basic_info': {'name': '平安银行', 'industry': '银行'},
        'market_data': {'price': 10.5, 'volume': 25000000}
    },
    '000002': {
        'basic_info': {'name': '万科A', 'industry': '房地产'},
        'market_data': {'price': 12.3, 'volume': 18000000}
    }
}

可以使用pandas.json_normalize()直接扁平化嵌套结构:

from pandas import json_normalize

# 扁平化嵌套字典并重置索引
df = json_normalize(stock_data_deep).reset_index().rename(columns={'index': 'stock_code'})

转换后的DataFrame会将嵌套字段展开为basic_info.name、market_data.price这类清晰的列名,结构规整易读。

总结
  • 单层嵌套:用pd.DataFrame.from_dict(data, orient='index').reset_index()快速调整结构
  • 多层嵌套:使用json_normalize()自动扁平化嵌套字段,无需手动拆解字典

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 06:10:50