创建M列的列表

时间:2019-01-24 11:41:58

标签: python pandas

我有此代码:

cleanData = cleanData.sort_values("Name")
        FinalGrade =computeFinalGrades(cleanData)
        studentList = cleanData["Studentid"].tolist()
        nameList = cleanData["Name"].tolist()
        gradelist1 = cleanData["Assignment1"].tolist()
        gradelist2 = cleanData["Assignment2"].tolist()
        gradelist3 = cleanData["Assignment3"].tolist()

        for i in range(len(studentList)):
            print(studentList[i], "  ", nameList[i], ":  ",gradelist1[i], ", ", gradelist2[i], ", ", gradelist3[i], ", ",  FinalGrade[i])

它给了我这个输出:

You have chosen to the show grade list for your file's data.
StudentID  Name                                    Final grade
s126519    Alberte Olsen :   2.0 ,  12.0 ,  0.0 ,  7.0
s123333    Alexander Hansen :   7.0 ,  12.0 ,  nan ,  12.0
s123789    Bettina Petersen :   12.0 ,  10.0 ,  10.0 ,  12.0
s128348    Ewan McGregor :   12.0 ,  nan ,  nan ,  12.0
s126734    Jepser Jespersen :   nan ,  nan ,  nan ,  -3.0
s121042    Josephine Brandt :   12.0 ,  12.0 ,  nan ,  12.0
s123235    Katinka Damgaard :   7.0 ,  7.0 ,  7.0 ,  7.0
s127110    Lise Christiansen :   -3.0 ,  -3.0 ,  -3.0 ,  -3.0
s123579    Marie Hansen :   10.0 ,  12.0 ,  nan ,  12.0
s123456    Michael Andersen :   7.0 ,  7.0 ,  4.0 ,  7.0
s124444    Nanna Nygaard :   10.0 ,  4.0 ,  4.0 ,  7.0
s121234    Natalie Sørensen :   4.0 ,  10.0 ,  nan ,  10.0
s128190    Sara Poulsen :   12.0 ,  12.0 ,  12.0 ,  12.0
s127698    Sebastian Bruun :   7.0 ,  10.0 ,  10.0 ,  10.0
s123468    Thomas Nielsen :   -3.0 ,  7.0 ,  2.0 ,  -3.0

它列出了StudentID,姓名,三个作业的成绩以及最终成绩。但是,我该如何编程,使其能够处理M份作业,因此,如果有5000份作业,我不必写gradelist5000?还有如何对齐数字,使其看起来更漂亮?

1 个答案:

答案 0 :(得分:0)

对于您指定的任务,无需显式迭代行。也不需要将每个系列转换为列表。只需指定列并使用print

首先将FinalGrade作为系列添加到数据框中。然后通过序列解压缩('Assignment'运算符)选择任意数量的*列:

cleanData['FinalGrade'] = computeFinalGrades(cleanData)
assignment_cols = [f'Assignment{i}' for i in range(1, 501)]
print(cleanData[['Studentid', 'Name', *assignment_cols, 'FinalGrade']])