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

如何将嵌套JSON提取至Pandas DataFrame?pd.json_normalize使用遇阻

如何将嵌套JSON提取为指定格式的Pandas DataFrame?

你的JSON数据存在动态嵌套键(比如date下的01_07_2020这类日期字符串),直接用pd.json_normalize无法自动解析这种结构,需要先手动遍历扁平化数据,再转换为DataFrame。

解决步骤

  1. 逐层遍历JSON的嵌套结构,提取所有传感器数据条目
  2. 合并每个传感器的基础字段与stats子字段,实现结构扁平化
  3. 转换为DataFrame并调整列顺序匹配预期格式

完整代码

import pandas as pd

# 假设原始JSON数据存储在变量raw_data中
all_sensor_entries = []

# 遍历外层年份分组
for year_group in raw_data["data"]:
    # 遍历date对象中的动态日期键(如01_07_2020)
    for date_key, customer_groups in year_group["date"].items():
        # 遍历每个客户的数据集
        for customer in customer_groups:
            # 遍历客户下的每个传感器数据
            for sensor in customer["data"]:
                # 合并sensor基础字段与stats子字段,移除stats层级
                combined_data = {**sensor, **sensor.pop("stats")}
                # 可选:按需添加日期、年份、客户ID等额外字段
                # combined_data["date"] = date_key
                # combined_data["year"] = year_group["year"]
                # combined_data["customerId"] = customer["customerId"]
                all_sensor_entries.append(combined_data)

# 转换为DataFrame并指定列顺序
result_df = pd.DataFrame(all_sensor_entries)[
    ["_id", "sensorType", "external", "min", "max", "avg", "diff", "last"]
]

print(result_df)

代码说明

  • 动态日期键通过year_group["date"].items()遍历处理,避免了静态键的依赖限制
  • 使用{**sensor, **sensor.pop("stats")}将stats中的字段直接提升到顶层,实现结构扁平化
  • 最后通过列索引筛选,确保输出的DataFrame列顺序与预期完全匹配

输出示例

_idsensorTypeexternalminmaxavgdifflast
5e1c75498de14f0bb5dFLAT0.019.520.7520.0714285714-7.947802197819.75
5efb44604bd91a7cde4cFLAT0.023.023.023.0null23.0
5efb44604bd9126e2de4dFLAT0.017.7519.7518.5833333333null17.75

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 13:10:38