You need to enable JavaScript to run this app. Pandas嵌套JSON DataFrame扁平化:转换为按事件类型分列的宽表
优惠活动
大模型
产品
解决方案
定价
更多

Pandas嵌套JSON DataFrame扁平化:转换为按事件类型分列的宽表

嵌套JSON转目标宽表的高效实现方案

直接用pd.json_normalize(data, 'eventConditions')提取得到的长表结构,后续要转成目标格式需要经过pivot、列层级重排、索引重置等多步操作,流程繁琐还容易出现值错位的问题。这里提供两种不需要复杂整形逻辑的实现方式:

方案1:逐行预拍平结构

提前按照目标列名规则,把每个条目下的嵌套条件直接转成单层字典,生成结果时不需要额外整形:

# 先定义固定的目标列顺序
target_cols = [
    "Category_matchType", "Category_expression",
    "Action_matchType", "Action_expression",
    "Label_matchType", "Label_expression"
]

processed_rows = []
for row_data in data:
    # 先初始化一行全为None的空值,避免缺字段时报错
    current_row = {col: None for col in target_cols}
    for cond in row_data["eventConditions"]:
        # 把事件类型枚举值转成对应列前缀,比如CATEGORY转成Category
        col_prefix = cond["type"].capitalize()
        current_row[f"{col_prefix}_matchType"] = cond["matchType"]
        current_row[f"{col_prefix}_expression"] = cond["expression"]
    processed_rows.append(current_row)

# 直接生成符合格式要求的宽表
final_df = pd.DataFrame(processed_rows, columns=target_cols)
  • 优势:逻辑完全可控,不会因为整形函数的默认行为出现值错位的问题,哪怕后续事件条件新增其他类型(比如新增TIME类型的规则),只要补充列名定义即可,维护成本极低。

方案2:简化版json_normalize一步拍平

如果不想写手动循环,也可以直接给json_normalize配置自定义的记录提取逻辑,一步生成拍平后的结构:

final_df = pd.json_normalize(
    data,
    record_path=lambda item: [
        {f"{cond['type'].capitalize()}_{field}": cond[field]
         for cond in item["eventConditions"]
         for field in ["matchType", "expression"]}
    ],
    errors="ignore"
)
# 按照目标列顺序重新排列即可
final_df = final_df[target_cols]
  • 优势:代码行数更少,不需要手动处理空值初始化的逻辑,适合快速开发场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.23 04:27:07