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

如何使用Pandas按State、City分组输出指定嵌套结构的JSON

实现方案

你之前的写法不符合预期,是因为直接对每个分组的子集调用to_json()会返回JSON字符串,最终得到的是带多级索引的Series结构,而非需要的嵌套对象数组。正确的做法是先构造符合预期结构的Python字典列表,再统一转成JSON格式。

完整可运行代码如下:

import pandas as pd
import json

df = pd.DataFrame({
    'State': ['PA', 'PA', 'PA', 'PA', 'PA', 'PA', 'PA', 'NY', 'NY', 'NY', 'NY', 'NY', 'NY', 'ME', 'ME', 'ME' ],
    'City': ['Philadelphia', 'Philadelphia', 'Philadelphia', 'Philadelphia', 'Scranton', 'Scranton', 'Williamsport', 'Buffalo', 'Buffalo', 'Buffalo', 'Buffalo', 'Albany', 'Albany', 'Portland', 'Portland', 'Ogunquit'],
    'Code': [10, 20, 30, 40, 50, 60, 10, 20, 30, 40, 50, 10, 20, 30, 40, 30],
    'Name': ['A', 'B', 'C', 'D', 'E', 'F', 'A', 'B', 'C', 'D', 'E', 'A', 'B', 'C', 'D', 'C'],
    'Rank': [1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 1, 2, 3, 4, 3]
})

# 分组构造目标结构
result = df.groupby(['State', 'City']).apply(
    lambda g: {
        'State': g.name[0],
        'City': g.name[1],
        'List': g[['Code', 'Name', 'Rank']].to_dict('records')
    }
).tolist()

# 输出带缩进的JSON字符串
json_output = json.dumps(result, indent=2, ensure_ascii=False)
print(json_output)

# 如果需要直接导出到文件可以用下面的代码
# with open('output.json', 'w', encoding='utf-8') as f:
#     json.dump(result, f, indent=2, ensure_ascii=False)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 22:18:03