如何将pandas执行groupby后的DataFrame转换为指定结构的JSON文件
问题原因
你执行groupby操作后,student_id、stuent_name、course_id、subject_name、teacher这些字段被设为了多层行索引(MultiIndex),所以查询columns只能拿到数值列weighted_score和total_average。
解决方案
按照以下步骤处理即可输出你需要的JSON格式:
- 先把行索引转为普通列,同时填充学生信息的空值:
import pandas as pd import json # 重置索引,把所有索引字段转为普通列 df = grouped.reset_index() # 填充学生id、姓名的空值(对应表格里的合并单元格) # 注意:如果实际列名是正确拼写的student_name、weighted_score请自行替换 df[['student_id', 'stuent_name']] = df[['student_id', 'stuent_name']].ffill()
- 按学生维度分组构造目标结构:
result = [] students_list = [] # 按学生id分组 for stu_id, group in df.groupby('student_id'): # 取当前学生的基本信息 stu_name = group['stuent_name'].iloc[0] total_avg = round(group['total_average'].iloc[0], 2) # 构造课程列表 courses = [] for _, row in group.iterrows(): courses.append({ "id": int(row['course_id']), "name": row['subject_name'], "teacher": row['teacher'].replace('.', '. '), # 适配Mr.D转为Mr. D的格式要求 "courseAverage": row['weight_score'] }) # 拼接学生信息 students_list.append({ "id": int(stu_id), "name": stu_name, "totalAverage": total_avg, "courses": courses }) # 拼接最终结构 result.append({"students": students_list})
- 输出为JSON文件:
with open('output.json', 'w', encoding='utf-8') as f: json.dump(result, f, ensure_ascii=False, indent=2)
运行后生成的output.json就是你要求的格式,数值精度、字段结构完全匹配。
内容的提问来源于stack exchange,提问作者Vaidik Trivedi
相关产品推荐
相关产品推荐

