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

Pandas带重复索引DataFrame转JSON报错,如何实现指定格式输出?

解决Pandas DataFrame转JSON时索引不唯一的报错问题

你的代码报错是因为将Client设为索引后,索引存在重复值,而to_json的多数orient参数要求索引必须唯一。要得到你期望的JSON格式,需要先对数据按Client分组聚合,再转换为JSON。

解决方案代码

import pandas as pd

# 初始化DataFrame
df = pd.DataFrame({'Client': [1, 1, 2, 2], 'Name': ['A', 'B', 'C', 'D']})
# 按Client分组,将Name列聚合为列表
grouped_df = df.groupby('Client')['Name'].agg(list).reset_index()
# 转换为指定格式的JSON
target_json = grouped_df.to_json(orient='records', indent=2)

print(target_json)

输出结果

[
  {
    "Client": 1,
    "Name": ["A", "B"]
  },
  {
    "Client": 2,
    "Name": ["C", "D"]
  }
]

关键说明

  • 先通过groupby('Client')['Name'].agg(list)将同一Client对应的Name合并为列表,解决了原数据中Client重复的问题。
  • reset_index()将Client从索引重新转为列,确保后续转JSON时结构符合预期。
  • 指定orient='records'会将DataFrame转换为对象数组的JSON格式,正好匹配你的需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 10:52:50