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

如何用Pandas从多层索引DataFrame生成嵌套JSON?

解决多层索引DataFrame转嵌套JSON的问题

要生成你需要的嵌套JSON结构,不用依赖to_json()的默认参数,而是可以结合groupby和字典推导式先构造出符合嵌套要求的Python字典,再转成JSON。

步骤示例:

  1. 先构造一个符合你场景的多层索引DataFrame(供测试):
import pandas as pd
import json

df = pd.DataFrame(
    {"foo": [6, 0, 5, 3, 1, 4], "bar": [0, 2, 0, 5, 3, 1]},
    index=pd.MultiIndex.from_tuples(
        [("a", 1), ("a", 2), ("a", 3), ("b", 1), ("b", 2), ("b", 3)],
        names=["top_level", "sub_level"]
    )
)
  1. 构造嵌套字典并转JSON:
# 按顶层索引分组,将每个子组转为以次级索引为key的字典
nested_data = {
    top_key: sub_df.to_dict("index") 
    for top_key, sub_df in df.groupby(level=0)
}

# 转为格式化的JSON字符串
output_json = json.dumps(nested_data, indent=2)
print(output_json)

输出结果:

{
  "a": {
    "1": {"foo": 6, "bar": 0},
    "2": {"foo": 0, "bar": 2},
    "3": {"foo": 5, "bar": 0}
  },
  "b": {
    "1": {"foo": 3, "bar": 5},
    "2": {"foo": 1, "bar": 3},
    "3": {"foo": 4, "bar": 1}
  }
}

关键说明:

  • groupby(level=0):按多层索引的第一层(顶层)分组,把每个顶层key对应的行单独提取为子DataFrame。
  • to_dict("index"):将子DataFrame转为字典,其中次级索引作为key,每行的列名和值组成的字典作为value,正好匹配你需要的嵌套层级。
  • 最后用json.dumps()把嵌套字典转成带格式的JSON字符串,方便其他脚本调用。

如果你的多层索引是列索引而非行索引,只需要先转置DataFrame(df.T),再执行上述逻辑即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 09:52:17