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

如何将Pandas DataFrame转换为指定结构的无列名JSON格式?

问题描述

现有如下格式的数据集:

Parameter    Value    Col3
A              1.0     2.0
B              1.0     2.5
dx             0.2     1.0

我使用以下Python脚本尝试将其保存为JSON格式:

# foo.py
import pandas
import json
# ...

df.to_json('foo.json'), orient='records', lines = True, indent=1)

当前输出的JSON格式为:

{
  "Parameter":"A",
  "Value":1.0,
  "Col3":2.0, 
 }

 {
  "Parameter":"B",
  "Value":1.0,
  "Col3" : 2.5,
 }

 {
  "Parameter":"dx",
  "Value":0.2,
  "Col3" : 2.5,
 }

期望得到的JSON格式如下:

{
        "A"    : [1.0, 2.0],
        "B"    : [1.0, 2.5],
        "dx"   : [0.2, 1.0]
}

需要实现该期望格式,同时要求能适配不同列名和列数的各类数据集。

解决方案

通过调整数据结构,将参数列设为索引后再转换为JSON即可实现需求,具体步骤如下:

  1. 读取数据集时,根据实际分隔符(此处为任意数量空格)正确解析表格;
  2. 将Parameter列设置为数据框的索引,作为JSON的键;
  3. 将每行的剩余列值转换为列表,作为对应键的值;
  4. 最后将处理后的字典导出为JSON文件,控制缩进格式。

完整代码示例:

import pandas as pd
import json

# 读取数据集,sep参数根据实际分隔符调整
df = pd.read_csv('your_data_file.txt', sep='\s+')

# 将Parameter列设为索引,把每行的其他列转为列表后转成字典
result_dict = df.set_index('Parameter').apply(list, axis=1).to_dict()

# 写入JSON文件,indent控制缩进空格数,ensure_ascii=False保留字符
with open('foo.json', 'w', encoding='utf-8') as f:
    json.dump(result_dict, f, indent=4, ensure_ascii=False)

适配说明

  • 无论数据集有多少列,只要第一列是参数名(列名为Parameter),剩余列的所有值都会自动打包成列表;
  • 如果参数列的列名不是Parameter,只需修改set_index中的列名即可,比如set_index('Param');
  • json.dump的indent参数可根据需求调整缩进空格数,匹配期望格式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 04:20:28