利用pandas解决问题:Firstly, input an integer � N, which represents a total of � N students. Then enter � N lines, each containing the student's name, class, exam 1 score, and exam 2 score. Count the average and total scores of each exam for each class, and
时间: 2024-02-01 17:03:19 浏览: 65
以下是用pandas解决该问题的代码实现:
``` python
import pandas as pd
# 读取学生信息
n = int(input())
data = []
for i in range(n):
line = input().split()
data.append(line)
# 创建DataFrame
df = pd.DataFrame(data, columns=['name', 'class', 'exam1', 'exam2'])
df[['exam1', 'exam2']] = df[['exam1', 'exam2']].astype(float)
# 计算各班级的平均分和总分
result = df.groupby('class').agg({'exam1': ['mean', 'sum'], 'exam2': ['mean', 'sum']})
# 输出结果
print(result)
```
上述代码首先读取学生信息,然后创建一个DataFrame。接着通过astype函数将考试成绩的数据类型转换为float类型。最后通过groupby函数对班级进行分组,并计算各班级的平均分和总分。最终输出结果。
阅读全文