已知学生成绩数据保存到score.json文件中,编写Python程序计算本人成绩的平均学分绩点(保留两位小数)、学分加权平均成绩(保留两位小数)、必修课程曾不及格学分,并保存到Excel文件中,名称为score.xlsx
时间: 2024-10-16 17:18:23 浏览: 41
基于python实现在excel中读取与生成随机数写入excel中
为了完成这个任务,我们可以使用Python的`json`模块读取`score.json`文件中的成绩数据,然后利用`pandas`库进行数据分析和处理。首先需要安装这两个库,如果还没有安装可以使用以下命令:
```bash
pip install pandas
pip install json
```
以下是一个简单的示例代码,假设`score.json`文件的结构如下:
```json
[
{"name": "张三", "scores": [{"course": "数学", "credit": 4, "grade": 85}, ...]},
{"name": "李四", "scores": [{"course": "语文", "credit": 3, "grade": 90}, ...]},
{"name": "王五", "scores": [{"course": "英语", "credit": 2, "grade": 78}, ...]}
]
```
```python
import json
import pandas as pd
# 读取json文件
with open('score.json', 'r') as f:
data = json.load(f)
# 创建一个DataFrame存储所有学生的数据
all_scores = pd.DataFrame(data)
# 计算平均学分绩点
def calculate_gpa(grades):
credit_sum = sum(score['credit'] for score in grades)
grade_sum = sum(score['grade'] * score['credit'] for score in grades)
return round(grade_sum / credit_sum, 2) if credit_sum else None
all_scores['GPA'] = all_scores.groupby('name')['scores'].apply(calculate_gpa)
# 计算学分加权平均成绩
all_scores['Weighted_Avg_Score'] = all_scores.apply(lambda row: sum(score['grade'] * score['credit'] for score in row['scores']) / sum(score['credit'] for score in row['scores']), axis=1)
# 检查并记录必修课不及格的学分
all_scores['Failed_Credits'] = all_scores['scores'].apply(lambda x: len([score for score in x if score['grade'] < 60 and '必修' in score['course']]), axis=1)
# 将结果保存到Excel文件
all_scores[['name', 'GPA', 'Weighted_Avg_Score', 'Failed_Credits']].to_excel('score.xlsx', index=False)
阅读全文