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

如何将Pandas DataFrame转换为指定格式的JSON输出?

实现Pandas DataFrame每行生成指定格式的JSON输出

问题背景

我编写了如下测试代码,生成包含col1、col2、col3、col4列的Pandas DataFrame:

import numpy as np
import pandas as pd
  
x = np.array([['101', 'title1', 'body1', 'answer1'], ['102', 'title2', 'body2', 'answer2'], ['103', 'title3', 'body3', 'answer3']])
   
df = pd.DataFrame(x, columns = ['col1', 'col2', 'col3', 'col4'])
df.head()

生成的DataFrame内容如下:

| col1 |col2   |col3   |col4
---------------------------------
0|  101 |title1 |body1  |answer1
1|  102 |title2 |body2  |answer2
2|  103 |title3 |body3  |answer3

希望为DataFrame中的每一行生成如下格式的JSON输出:

{"index": {"_id": "col1"}}
{"title": "col2", "body": "col3", "answer": "col4"}

例如第一行对应的输出为:

{"index": {"_id": "101"}}
{"title": "title1", "body": "body1", "answer": "answer1"}

解决方案

方法1:逐行遍历生成JSON

逻辑直观,适合小数据集,直接遍历每行构造JSON:

import json

for _, row in df.iterrows():
    # 构造index行的字典并转JSON
    index_json = json.dumps({"index": {"_id": row['col1']}})
    # 构造内容行的字典并转JSON
    content_json = json.dumps({"title": row['col2'], "body": row['col3'], "answer": row['col4']})
    # 输出两行JSON
    print(index_json)
    print(content_json)

方法2:用apply批量生成完整输出

可以一次性生成所有内容,方便写入文件:

import json

def row_to_json_pair(row):
    index_line = json.dumps({"index": {"_id": row['col1']}})
    content_line = json.dumps({"title": row['col2'], "body": row['col3'], "answer": row['col4']})
    return f"{index_line}\n{content_line}"

# 生成所有行的JSON内容并合并
full_output = '\n'.join(df.apply(row_to_json_pair, axis=1))
# 打印或写入文件
print(full_output)
# 写入文件示例:
# with open('output.json', 'w', encoding='utf-8') as f:
#     f.write(full_output)

方法3:高效批量处理(适合大数据集)

通过向量化操作减少循环开销,提升处理效率:

import json

# 批量生成index行的JSON字符串
index_lines = df['col1'].apply(lambda x: json.dumps({"index": {"_id": x}}))
# 批量生成内容行的JSON字符串
content_lines = df.apply(lambda row: json.dumps({"title": row['col2'], "body": row['col3'], "answer": row['col4']}), axis=1)

# 交替合并两类行
combined = []
for idx in range(len(index_lines)):
    combined.append(index_lines.iloc[idx])
    combined.append(content_lines.iloc[idx])

full_output = '\n'.join(combined)
print(full_output)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 09:50:17