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

Python实现Excel与JSON学生信息匹配,高效补充CourseLoad字段

高效实现JSON与Excel数据的姓名匹配补充

针对数百条数据的场景,用字典构建姓名到课程负载的映射表是最优方案——字典的查找操作时间复杂度为O(1),整体流程的时间复杂度为O(n+m)(n为JSON数据量,m为Excel数据量),远优于暴力嵌套循环的O(n*m)。

实现步骤与代码

使用json库处理JSON文件,pandas库读取Excel(处理表格数据高效便捷):

  1. 导入依赖库
import json
import pandas as pd
  1. 读取并加载JSON数据
# 读取原始JSON文件
with open('students.json', 'r', encoding='utf-8') as json_file:
    student_list = json.load(json_file)
  1. 读取Excel并构建姓名映射字典
# 读取Excel表格,假设姓名列名为"Name",课程负载列名为"CourseLoad"
course_df = pd.read_excel('student_courses.xlsx')
# 构建姓名到CourseLoad的映射字典
course_map = course_df.set_index('Name')['CourseLoad'].to_dict()
  1. 高效匹配并补充数据
# 遍历JSON中的学生数据,通过字典直接查找匹配
for student in student_list:
    student_name = student.get('Name')
    # 存在匹配项则补充CourseLoad,无匹配则设为None(可按需调整)
    student['CourseLoad'] = course_map.get(student_name, None)
  1. 将更新后的数据写入新JSON文件
with open('updated_students.json', 'w', encoding='utf-8') as output_file:
    json.dump(student_list, output_file, ensure_ascii=False, indent=4)

优化细节:避免匹配误差

如果存在姓名大小写不一致、前后空格等情况,可对姓名做预处理,确保匹配准确性:

# 预处理Excel中的姓名:去除空格、转小写
course_df['Name'] = course_df['Name'].str.strip().str.lower()
course_map = course_df.set_index('Name')['CourseLoad'].to_dict()

# 遍历JSON时同步预处理姓名
for student in student_list:
    raw_name = student.get('Name')
    if raw_name:
        processed_name = raw_name.strip().lower()
        student['CourseLoad'] = course_map.get(processed_name, None)
    else:
        student['CourseLoad'] = None

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 06:55:09