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

嵌套字典转Pandas DataFrame时from_dict返回空数据框如何解决

问题原因

当使用pd.DataFrame.from_dict()并指定orient="index"时,pandas会将字典每个键对应的value拆分为多个列的值。你当前字典的每个值是嵌套字典结构,pandas会默认把嵌套字典的键($USD、Apple、MSFT)识别为列名,对应的值识别为列值。此时强制指定columns=["holdings"],pandas无法在嵌套字典中找到匹配的列名,就会返回无数据的空DataFrame。

解决方案

有两种常用的实现方式,都可以达到把datetime键作为行索引、嵌套字典存入holdings列的需求:

  • 方法1:通过Series中转实现(代码最简)
import pandas as pd
import datetime

# 你的原始字典
holdings_dict = {
    datetime.datetime(2021, 8, 27, 4, 10, 15, 180064, tzinfo=datetime.timezone.utc): {
        "$USD": "158.1727087865",
        "Apple": "3",
        "MSFT": "3",
    }
}

df = pd.Series(holdings_dict).to_frame('holdings')
  • 方法2:调整字典结构后使用from_dict
# 先把每个值包装为列表,让pandas将其识别为单列的内容
processed_dict = {k: [v] for k, v in holdings_dict.items()}
df = pd.DataFrame.from_dict(processed_dict, orient="index", columns=["holdings"])

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 13:06:04