从一组分数计算不及格分数的CSV文件

2024-05-16 12:35:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个CSV文件,它的当前格式如下。在

一个两行的例子是:

first_Name  last_Name   test1   test2   test3   test4
Alex        Brian       11      17      13      24
Pete        Tong        19      14      12      30

现在我的代码不工作,简单地说,我不确定我是否在正确的轨道上。 我的当前代码:

^{pr2}$

我还有这一行代码,它是用来读取CSV文件的,并显示在输出窗口中。在

with open("studentGradeFrom.csv") as csvfile:
    readFile = csv.reader(csvfile, delimiter=",", quotechar="¦")
    for row in readFile:
        print(row)

然而,由于我是Python新手,我正在寻找帮助来创建一个Python脚本,该脚本将查看结果并进行计算,以告诉我学生是否通过或失败。 我希望这是在一个单独的文件。所以我想我需要读写一个不同的CSV文件,以显示一个学生是否失败或有一个整体通过百分比。在

with open("studentGradeTo.csv", 'w') as avg: #used to write to after the calculation is complete
    loadeddata = open("studentGradeFrom.csv", 'r') #used to read the data from the CSV before calculation.
    writer=csv.writer(avg)
    readloaded=csv.reader(loadeddata)
    listloaded=list(readloaded)

现在我的问题是:我要怎么做呢,从一个大约50个不同学生的文件中查看数据。而不改变读取的CSV与学生成绩,只改变CSV文件显示及格或不及格成绩。任何帮助都将不胜感激。在

编辑:我忘了说第一次考试是期末成绩的20%,第二次考试和第三次考试都是一样的。这三项总计占期末成绩的60%。而第四次考试占期末成绩的40%。在


Tags: 文件csvthetocsvfile代码nameas
2条回答

下面是一个仅使用csv库的概念的快速示例(您当然可以优化很多这方面的内容,但它应该适用于示例)。在

import csv

student_grades = []

# First open up your file containing the raw student grades
with open("studentGradeFrom.csv", "r") as file:
    # Setup your reader with whatever your settings actually are
    csv_file = csv.DictReader(file, delimiter=",", quotechar='"')

    # Cycle through each row of the csv file
    for row in csv_file:
        # Calculate the numerical grade of the student
        grade = grader(
            int(row["test1"]),
            int(row["test2"]),
            int(row["test3"]),
            int(row["test4"])
        )

        # Calculate the letter score for the student
        score = gradeScores(grade)

        # Assemble all the data into a dictionary
        # Only need to save fields you need in the final output
        student_grades.append({
            "first_name": row["first_name"],
            "last_name": row["last_name"],
            "test1": row["test1"],
            "test2": row["test2"],
            "test3": row["test3"],
            "test4": row["test4"],
            "grade": grade,
            "score": score
        })

# Open up a new csv file to save all the grades
with open("studentGradeFrom.csv", "w", newline="") as file:
    # List of column names to use as a header for the file
    # These will be used to match the dictionary keys set above
    # Only need to list the fields you saved above
    column_names = [
        "first_name", "last_name", "test1", "test2", "test3",
        "test4", "grade", "score"
    ]

    # Create the csv writer, using the above headers
    csv_file = csv.DictWriter(file, column_names)

    # Write the header
    csv_file.writeheader()

    # Write each dictionary to the csv file
    for student in student_grades:
        csv_file.writerow(student)

您需要根据您的具体要求对其进行微调,但希望它能让您朝着正确的方向前进。如果您需要一个特定的引用:https://docs.python.org/3.6/library/csv.html,那么大部分都会记录在官方文档中。在

这种任务适合pandas库。在

这里有一个解决方案,当您的需求发生变化时,它是可以适应的。在

import pandas as pd

df = pd.read_csv('studentGradeFrom.csv')

#   first_Name last_Name  test1  test2  test3  test4
# 0       Alex     Brian     11     17     13     24
# 1       Pete      Tong     19     14     12     30

boundaries = {(90, 100.01): 'A',
              (80, 90): 'B',
              (70, 80): 'C',
              (60, 70): 'D',
              (0, 60): 'F'}

def grade_calc(x, b):
    return next((v for k, v in b.items() if k[0] <= x <= k[1]), None)

df['FinalMark'] = 0.2*df['test1'] + 0.2*df['test2'] + 0.2*df['test3'] + 0.4*df['test4']
df['FinalGrade'] = df['FinalMark'].apply(grade_calc, b=boundaries)

#   first_Name last_Name  test1  test2  test3  test4  FinalMark FinalGrade
# 0       Alex     Brian     11     17     13     24       17.8          F
# 1       Pete      Tong     19     14     12     30       21.0          F

df.to_csv('studentGradeTo.csv', index=False)

相关问题 更多 >