Statistical score Statistics the scores of different classes and exams. Input&Output 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. Input 5 Alice,Class A,80,85 Bob,Class B,70,75 Bob2,Class B,70,75 Bob3,Class B,70,75 Charlie,Class A,90,95 Output class score1_mean score1_sum score2_mean score2_sum 0 Class A 85.0 170 90.0 180 1 Class B 70.0 210 75.0 225 use pandas in python
时间: 2024-01-29 22:03:43 浏览: 109
srilm 和 tcl8.6.12.zip
Sure! Here's an example code using pandas in Python to solve the problem you described:
```python
import pandas as pd
# Read input values
n = int(input())
data = []
for i in range(n):
name, cls, score1, score2 = input().split(',')
data.append({'name': name, 'class': cls, 'score1': int(score1), 'score2': int(score2)})
# Create a DataFrame with the input data
df = pd.DataFrame(data)
# Group by class and calculate the mean and sum for each exam
grouped = df.groupby('class').agg({'score1': ['mean', 'sum'], 'score2': ['mean', 'sum']})
# Flatten the column names and reset the index
grouped.columns = ['_'.join(col).strip() for col in grouped.columns.values]
grouped = grouped.reset_index()
# Print the result
print(grouped)
```
The code reads the input values, creates a pandas DataFrame with the data, groups it by class, calculates the mean and sum for each exam, and prints the result sorted by class name. Note that the column names are flattened and the index is reset to make the output format match the one in your example.
阅读全文