我正在构建一个程序,提示用户加载csv文件。 csv文件始终包含列StudentID,名称,工作分配1、2、3 ... 工作分配的数量。
我试图显示一个名称列表,其中每个作业都有一个等级,最后一个等级是从导入的函数computeFinalGrade计算得出的。
如何更改代码的最后一行以打印正确数量的作业的成绩和最终成绩?
所需的输出: 如果csv仅具有“ Assignment1”,则输出应为:
“迈克尔·安徒生(Michael Andersen)获得了10年级。最终成绩为10分”。
如果csv包含5个分配,则输出应为:
“ Michael Andersen获得了10,7,12,7,10的分数。最终的分数是10”
我的代码:
useEffect
答案 0 :(得分:1)
使用:
df = pd.read_csv(filename,sep=';')
#filter DataFrame by positions
df1 = df.iloc[:,2:]
#count computeFinalGrades
f = computeFinalGrades(df1.values)
#all Assignments convert to joined string
df['Assignment'] = df1.astype(str).apply(', '.join, axis=1)
df['FinalGrade'] = f
#zip columns together and loop
for name, assign, final in zip(df['Name'],df['Assignment'],df['FinalGrade']):
#python 3.6+ f-strings
print(f'{name} has obtained the grades {assign}. The final grade is {final}')
#python bellow with format
print('{} has obtained the grades {}. The final grade is {}'.format(name, assign, final))
示例:
df = pd.DataFrame({
'Name':list('abcd'),
'StudentID':[7,8,9,4],
'Assignment1':[1,3,5,7],
'Assignment2':[5,3,6,9],
})
print (df)
Name StudentID Assignment1 Assignment2
0 a 7 1 5
1 b 8 3 3
2 c 9 5 6
3 d 4 7 9
#sample function
def computeFinalGrades(x):
return x.sum()
#filter DataFrame by positions
df1 = df.iloc[:,2:]
#count computeFinalGrades
f = computeFinalGrades(df1.values)
#all Assignments convert to joined string
df['Assignment'] = df1.astype(str).apply(', '.join, axis=1)
df['FinalGrade'] = f
print (df)
Name StudentID Assignment1 Assignment2 Assignment FinalGrade
0 a 7 1 5 1, 5 39
1 b 8 3 3 3, 3 39
2 c 9 5 6 5, 6 39
3 d 4 7 9 7, 9 39
for name, assign, final in zip(df['Name'],df['Assignment'],df['FinalGrade']):
print(f'{name} has obtained the grades {assign}. The final grade is {final}')
a has obtained the grades 1, 5. The final grade is 39
b has obtained the grades 3, 3. The final grade is 39
c has obtained the grades 5, 6. The final grade is 39
d has obtained the grades 7, 9. The final grade is 39