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

如何将DataFrame转换为指定结构的嵌套JSON对象?技术求助

解决方案

你可以通过遍历DataFrame的每一行,将每行数据拆分为两个子对象,再组合成目标嵌套结构,最后转为JSON。具体代码如下:

import pandas as pd
import json

# 假设你的DataFrame是global_line
global_line = pd.DataFrame({
    'name': ['LCL', 'UCL', 'CL'],
    'value': [0.205512, 0.327907, 0.269737],
    'xAxis1': [0, 0, 0],
    'yAxis1': [0.205512, 0.327907, 0.269737],
    'xAxis2': [200, 200, 200],
    'yAxis2': [0.205512, 0.327907, 0.269737],
    'lineStyle': [{'type': 'dashed'}]*3
})

# 构建目标结构
result = {
    "data": [
        [
            {
                "name": row['name'],
                "xAxis1": row['xAxis1'],
                "yAxis1": row['yAxis1'],
                "lineStyle": row['lineStyle']
            },
            {
                "xAxis2": row['xAxis2'],
                "yAxis2": row['yAxis2']
            }
        ]
        for _, row in global_line.iterrows()
    ]
}

# 转为格式化的JSON字符串
json_result = json.dumps(result, indent=4)
print(json_result)

代码说明

  • 遍历global_line的每一行,对每行数据拆分出两个子对象:第一个包含name、xAxis1、yAxis1和lineStyle,第二个只保留xAxis2和yAxis2
  • 把这两个子对象放进一个数组,所有行的数组再汇总到外层的data数组中
  • 最后用json.dumps把结构转为格式化的JSON字符串,方便查看和使用

输出结果

运行后会得到你期望的嵌套结构:

{
    "data": [
        [
            {
                "name": "LCL",
                "xAxis1": 0,
                "yAxis1": 0.205512,
                "lineStyle": {
                    "type": "dashed"
                }
            },
            {
                "xAxis2": 200,
                "yAxis2": 0.205512
            }
        ],
        [
            {
                "name": "UCL",
                "xAxis1": 0,
                "yAxis1": 0.327907,
                "lineStyle": {
                    "type": "dashed"
                }
            },
            {
                "xAxis2": 200,
                "yAxis2": 0.327907
            }
        ],
        [
            {
                "name": "CL",
                "xAxis1": 0,
                "yAxis1": 0.269737,
                "lineStyle": {
                    "type": "dashed"
                }
            },
            {
                "xAxis2": 200,
                "yAxis2": 0.269737
            }
        ]
    ]
}

额外建议

如果你的DataFrame数据量很大,iterrows()效率会偏低,可以改用apply方法结合lambda函数来提升性能:

result = {
    "data": global_line.apply(
        lambda row: [
            {
                "name": row['name'],
                "xAxis1": row['xAxis1'],
                "yAxis1": row['yAxis1'],
                "lineStyle": row['lineStyle']
            },
            {
                "xAxis2": row['xAxis2'],
                "yAxis2": row['yAxis2']
            }
        ],
        axis=1
    ).tolist()
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 20:39:19