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

如何用Pandas自动扁平化多层嵌套JSON,无需手动指定Meta字段?

自动展平多层嵌套JSON为Pandas DataFrame

如果你不想手动指定pd.json_normalize的meta参数,可以通过递归遍历JSON结构,自动收集所有父级字段并生成扁平化的字典列表,再转换为DataFrame。这种方法适用于任意深度的嵌套JSON,无需手动配置分支路径。

实现步骤

  1. 递归遍历JSON:编写递归函数遍历JSON的每个层级,将父级字段与子级字段合并,为每个最内层条目(如示例中的material)生成包含所有上下文的字典。
  2. 转换为DataFrame:将扁平化的字典列表直接转换为Pandas DataFrame,自动处理所有字段路径。

完整代码示例

import pandas as pd

def flatten_nested_json(data):
    flattened_items = []
    
    def recurse(node, parent_dict, parent_path):
        if isinstance(node, list):
            for item in node:
                recurse(item, parent_dict.copy(), parent_path)
        elif isinstance(node, dict):
            current_dict = parent_dict.copy()
            scalars = {}
            nested = {}
            
            for key, value in node.items():
                # 构建当前字段的完整路径
                current_path = f"{parent_path}.{key}" if parent_path else key
                if isinstance(value, (list, dict)):
                    nested[(key, current_path)] = value
                else:
                    scalars[current_path] = value
            
            # 将当前层级的标量字段加入字典
            current_dict.update(scalars)
            
            # 如果没有嵌套结构,将当前字典加入结果列表
            if not nested:
                flattened_items.append(current_dict)
                return
            
            # 递归处理嵌套结构
            for (key, path), value in nested.items():
                recurse(value, current_dict.copy(), path)
    
    # 从顶层数组开始遍历
    recurse(data['building_element_group'], {}, "")
    return flattened_items

# 示例JSON数据(替换为你的实际数据)
json_data = {
  "building_element_group": [
    {
      "basetype": "facade",
      "building_element": [
        {
          "type": "Unitised",
          "functional_unit": "m2",
          "quantity": 5.74,
          "element": [
            {
              "id": "13d22d3b-7fc6-4116-93ad-80c139e006dc",
              "type": "glazing",
              "quantity_unit": "m2",
              "quantity": 3.29,
              "material": [
                {
                  "type": "glass",
                  "impact_data_ID": "5726d14e-d36e-417d-afc4-c70793080186",
                  "quantity_unit": "m2/m2",
                  "quantity": 1
                }
              ]
            },
            {
              "id": "045d27e6-8397-4672-9f4a-6cbc5fe4e716",
              "type": "cladding",
              "quantity_unit": "m2",
              "quantity": 6.27,
              "material": [
                {
                  "type": "terracotta",
                  "impact_data_ID": "529d8876-6adb-449c-a12a-74c56aaadc4f",
                  "quantity_unit": "m/m2",
                  "quantity": 0.04
                },
                {
                  "type": "brick",
                  "impact_data_ID": "e28d29a9-38f8-4684-a6b1-0615ac7f66e5",
                  "quantity_unit": "m/m2",
                  "quantity": 0.06
                },
                {
                  "type": "GRC",
                  "impact_data_ID": "5043ffe6-9d2e-448e-83ed-f36f1f5decfc",
                  "quantity_unit": "m/m2",
                  "quantity": 0.025
                },
                {
                  "type": "Fiber cement",
                  "impact_data_ID": "53bbd2be-f9ac-4ee7-88f3-34df68ee5187",
                  "quantity_unit": "m/m2",
                  "quantity": 0.013
                }
              ]
            }
          ]
        }
      ]
    }
  ]
}

# 生成扁平化字典列表并转换为DataFrame
flattened_data = flatten_nested_json(json_data)
df = pd.DataFrame(flattened_data)

# 查看结果
print(df.head())

说明

  • 字段命名:每个字段的列名采用完整路径(如building_element.element.type),避免重复键名冲突,与pd.json_normalize的sep参数效果一致。
  • 兼容性:支持任意深度的嵌套数组和字典,缺失字段会自动填充为NaN。
  • 无需手动配置:无需指定record_path或meta参数,函数会自动识别所有层级的字段。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 11:40:25