2017-02-25 6 views
1

私は3つの課題と1つのテストの得点を合計し、自分のデータフレームから得点(A、B、C、D、F)スコア。このコードを書くための効率的でクリーンな方法 - Pandas

これは私のデータフレームです。

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) 
を生成するために私のコードです

私のコードは非常に汚れた探しています。私は、このコードに似た機能を持つコードを書く良い方法があるはずです。

ご連絡ください。

ありがとうございました!

答えて

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 
+1

ああ、すごい、これをすごい。ありがとう、私も新しいことを学びました。 –

+0

@ Niche.P、うれしい – MaxU

関連する問題