利用panda解决以下问题: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 sort the results by class name before outputting them to the console. Output includes class, score1_mean, score1_sum, score2_mean, score2_sum.
时间: 2023-12-18 15:05:48 浏览: 61
以下是使用 Pandas 解决该问题的代码:
```python
import pandas as pd
# 输入学生人数
N = int(input("请输入学生人数:"))
# 输入每个学生的信息
students = []
for i in range(N):
name, cls, score1, score2 = input().split()
students.append({
"name": name,
"class": cls,
"score1": int(score1),
"score2": int(score2)
})
# 将学生信息转换成 DataFrame
df = pd.DataFrame(students)
# 按班级分组,计算平均分和总分
grouped = df.groupby("class").agg({
"score1": ["mean", "sum"],
"score2": ["mean", "sum"]
})
# 对结果进行排序
grouped = grouped.sort_index()
# 输出结果
print(grouped)
```
运行该程序后,会先要求输入学生人数,然后再输入每个学生的信息。接着,程序会将学生信息转换成 Pandas DataFrame,并按班级分组,计算每个班级每门考试的平均分和总分。最后,程序对结果按班级名称进行排序,并输出到控制台上。
相关问题
利用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
以下是用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函数对班级进行分组,并计算各班级的平均分和总分。最终输出结果。
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 sort the results by class name before outputting them to the console. Output includes class, score1_mean, score1_sum, score2_mean, score2_sum.
以下是使用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']})
# 对结果按班级名称排序
result = result.sort_values(by='class')
# 输出结果
print(result.to_string(header=['score1_mean', 'score1_sum', 'score2_mean', 'score2_sum'], \
formatters={'score1_mean': '{:.2f}'.format, 'score1_sum': '{:.2f}'.format, \
'score2_mean': '{:.2f}'.format, 'score2_sum': '{:.2f}'.format}))
```
上述代码与前面的代码实现基本相同,但是在最后输出结果时使用了to_string函数,并指定header和formatters参数,以便将结果输出为指定格式。同时对结果按班级名称进行了排序。最终输出结果。
阅读全文