以Python代码的方式读取文件score.csv中的成绩数据,计算平均分并统计其中语文成绩大于等于80,英语成绩大于等于85的学生每门课程的成绩(结果按平均分从大到小排序),将结果输出至文件result.csv中。并绘制满足条件的学生平均成绩柱状图
时间: 2024-03-21 20:38:32 浏览: 114
python 常用 示例 数据 train.csv eval.csv titanic.csv
好的,以下是Python代码实现,包括绘制柱状图的部分:
```python
import csv
import matplotlib.pyplot as plt
# 读取score.csv文件中的成绩数据
with open('score.csv', 'r', encoding='utf-8-sig') as f:
reader = csv.DictReader(f)
scores = [row for row in reader]
# 计算平均分
total_score = [float(score['语文']) + float(score['数学']) + float(score['英语']) for score in scores]
average_score = sum(total_score) / len(total_score)
# 统计语文成绩大于等于80,英语成绩大于等于85的学生每门课程的成绩
high_scores = []
for score in scores:
if float(score['语文']) >= 80 and float(score['英语']) >= 85:
high_scores.append({
'姓名': score['姓名'],
'语文': float(score['语文']),
'数学': float(score['数学']),
'英语': float(score['英语']),
'平均分': (float(score['语文']) + float(score['数学']) + float(score['英语'])) / 3
})
# 按平均分从大到小排序
high_scores = sorted(high_scores, key=lambda x: x['平均分'], reverse=True)
# 将结果输出至文件result.csv中
with open('result.csv', 'w', encoding='utf-8-sig', newline='') as f:
writer = csv.DictWriter(f, fieldnames=['姓名', '语文', '数学', '英语', '平均分'])
writer.writeheader()
for score in high_scores:
writer.writerow(score)
# 绘制柱状图
names = [score['姓名'] for score in high_scores]
chinese_scores = [score['语文'] for score in high_scores]
math_scores = [score['数学'] for score in high_scores]
english_scores = [score['英语'] for score in high_scores]
average_scores = [score['平均分'] for score in high_scores]
plt.figure(figsize=(10, 5))
plt.bar(names, chinese_scores, label='语文')
plt.bar(names, math_scores, bottom=chinese_scores, label='数学')
plt.bar(names, english_scores, bottom=[x + y for x, y in zip(chinese_scores, math_scores)], label='英语')
plt.bar(names, average_scores, color='red', label='平均分')
plt.xlabel('姓名')
plt.ylabel('成绩')
plt.title('满足条件的学生成绩柱状图')
plt.legend()
plt.show()
```
注意:在运行代码之前,需要先安装matplotlib库。
阅读全文