我一直在研究这个代码,它总结了我的数据框中的3个分配和1个测试的分数,并根据分数生成标记(A,B,C,D,F)。
这是我的数据框架。
StudentId, Assignment1, Assignment2, Assignment3, Test
xxxxxxxx 11 15 7 50
yyyyyyyy 5 10 2 31
这是我总结分数和生成标记的代码
SumScoreX = []
GradeX = []
for x in xrange(len(df)):
A1, A2, A3, T1 = df['Assignment1'][x], df['Assignment2'][x],df['Assignment3'][x], df['Test'][x]
SumScore = np.sum([A1,A2,A3,T1])
if SumScore < 51:
Grade = 'F'
elif SumScore == 50 and SumScore < 60:
Grade = 'D'
elif SumScore == 60 and SumScore < 70:
Grade = 'C'
elif SumScore == 70 and SumScore < 80:
Grade = 'B'
elif SumScore <= 80:
Grade = 'A'
SumScoreX.append(np.round(SumScore))
GradeX.append(Grade)
我的代码看起来非常不干净。我觉得应该有一种更好的方法来编写与此代码具有类似功能的代码。
请告诉我。
谢谢!
答案 0 :(得分:2)
假设你有以下DF:
In [100]: df
Out[100]:
StudentId Assignment1 Assignment2 Assignment3 Test
0 xxxxxxxx 11 15 7 50
1 yyyyyyyy 5 10 2 31
首先计算score
:
In [101]: df['score'] = df.filter(regex=r'(?:Assignment\d*|Test)').sum(1)
现在我们可以使用pd.cut()方法对分数进行分类:
In [102]: df['grade'] = pd.cut(df.score, bins=[0, 51, 60, 70, 80, 200], labels=list('FDCBA'))
In [103]: df
Out[103]:
StudentId Assignment1 Assignment2 Assignment3 Test score grade
0 xxxxxxxx 11 15 7 50 83 A
1 yyyyyyyy 5 10 2 31 48 F