You need to enable JavaScript to run this app. 如何基于pandas DataFrame唯一列转指定结构JSON并反向还原
优惠活动
大模型
产品
解决方案
定价
更多

如何基于pandas DataFrame唯一列转指定结构JSON并反向还原

实现代码

前置依赖

沿用你提供的测试数据,导入所需库:

import json
import numpy as np
import pandas as pd

# 测试DataFrame
data_dictionary = {'col_1':[np.nan,np.nan,np.nan,np.nan],
                   'col_2':[np.nan,1,np.nan,1],
                   'col_3':['a','b','c','d'],
                   'col_4':['description of a','description of b','description of c','description of d']}
df = pd.DataFrame(data_dictionary)

DataFrame转目标结构JSON

实现带合法性校验的转换函数,严格匹配指定的JSON格式:

def df_to_target_json(df: pd.DataFrame, id_col: str, save_path: str):
    # 前置校验
    if id_col not in df.columns:
        raise ValueError(f"指定的标识符列{id_col}不在DataFrame列中")
    if not df[id_col].is_unique:
        raise ValueError(f"标识符列{id_col}存在重复值,不符合结构要求")
    
    # 构造目标字典骨架
    json_struct = {id_col: {}}
    # 按DataFrame原始行顺序逐行遍历
    for _, row in df.iterrows():
        current_id = row[id_col]
        current_row_mapping = {}
        # 按原始列顺序构造非标识符列的键值对
        for col in df.columns:
            if col == id_col:
                continue
            cell_val = row[col]
            # 将pandas空值转为Python None,序列化后自动输出JSON格式的null
            current_row_mapping[col] = None if pd.isna(cell_val) else cell_val
        json_struct[id_col][current_id] = current_row_mapping
    
    # 写入JSON文件,保留缩进、不转义中文
    with open(save_path, 'w', encoding='utf-8') as f:
        json.dump(json_struct, f, ensure_ascii=False, indent=2)

调用测试:

df_to_target_json(df, id_col="col_3", save_path="target.json")

生成的target.json结构和你给出的示例完全一致。

从JSON还原原始DataFrame

实现反向解析函数:

def target_json_to_df(json_path: str) -> pd.DataFrame:
    with open(json_path, 'r', encoding='utf-8') as f:
        json_struct = json.load(f)
    
    # 提取标识符列名(最外层唯一键)
    id_col = next(iter(json_struct.keys()))
    id_mapping = json_struct[id_col]
    
    reconstructed_rows = []
    # 按JSON中标识符的原始顺序遍历(Python3.7+字典默认保留插入顺序)
    for id_val, row_content in id_mapping.items():
        # 为每行补上标识符列的取值
        row = row_content.copy()
        row[id_col] = id_val
        reconstructed_rows.append(row)
    
    # 构造DataFrame,pandas自动将JSON的null转回对应空值
    return pd.DataFrame(reconstructed_rows)

注意事项

  • 由于目标JSON结构的约束,还原后的DataFrame中,标识符列会位于所有非标识符列的末尾。如果需要严格对齐原始列顺序,需在结构中额外补充列顺序元数据,会超出当前指定的JSON格式范围。
  • JSON序列化不会保留原始列的数据类型,还原时pandas会自动推断列类型,常规场景下和原始列类型一致;若存在全空列、特殊类型列的严格类型对齐需求,同样需要在JSON中补充类型元数据。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.17 19:36:04