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

如何将Pandas DataFrame多列合并为JSON格式的单列

解决方案

以下是两种高效实现需求的方法,均基于Pandas内置功能:

方法一:使用Pandas原生to_json(无需额外导入库)

import pandas as pd

# 构造示例DataFrame(如果已有数据可跳过此步)
df = pd.DataFrame({
    'Main Key': ['First', 'Second', 'Third', 'Fourth'],
    'Second': ['A', 'B', 'C', 'D'],
    'Column A': ['Value 1', 'Value 6', 'Value 11', 'Value 16'],
    'Column B': ['Value 2', 'Value 7', 'Value 12', 'Value 17'],
    'Column C': ['Value 3', 'Value 8', 'Value 13', 'Value 18'],
    'Column D': ['Value 4', 'Value 9', 'Value 14', 'Value 19'],
    'Column E': ['Value 5', 'Value 10', 'Value 15', 'Value 20']
})

# 新增聚合列:将Column A至E转为JSON字符串
df['Aggregated Data'] = df[['Column A', 'Column B', 'Column C', 'Column D', 'Column E']].apply(lambda row: row.to_json(), axis=1)

# 保留目标列生成最终结果
result_df = df[['Main Key', 'Second', 'Aggregated Data']]

# 查看结果
print(result_df)

方法二:结合to_dict与json.dumps(灵活控制JSON格式)

如果需要对JSON输出做更多自定义(比如处理特殊字符、缺失值),可以用这个方法:

import pandas as pd
import json

# 构造示例DataFrame(同上)
df = pd.DataFrame({
    'Main Key': ['First', 'Second', 'Third', 'Fourth'],
    'Second': ['A', 'B', 'C', 'D'],
    'Column A': ['Value 1', 'Value 6', 'Value 11', 'Value 16'],
    'Column B': ['Value 2', 'Value 7', 'Value 12', 'Value 17'],
    'Column C': ['Value 3', 'Value 8', 'Value 13', 'Value 18'],
    'Column D': ['Value 4', 'Value 9', 'Value 14', 'Value 19'],
    'Column E': ['Value 5', 'Value 10', 'Value 15', 'Value 20']
})

# 新增聚合列
df['Aggregated Data'] = df[['Column A', 'Column B', 'Column C', 'Column D', 'Column E']].apply(
    lambda row: json.dumps(row.to_dict(), ensure_ascii=False),  # ensure_ascii=False支持中文等非ASCII字符
    axis=1
)

# 生成最终结果
result_df = df[['Main Key', 'Second', 'Aggregated Data']]

关键逻辑说明

  • df[['Column A', ..., 'Column E']]:精准选中需要聚合的列
  • apply(..., axis=1):按行遍历处理数据
  • row.to_json() / json.dumps(row.to_dict()):将每行数据转为标准JSON格式的字符串

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 09:40:25