Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Convert an array with marks into an array with letter marks numpy

Here I tried to return an array in letter grade, but it returns only a letter Grade.
I need to get the whole numpz array in letter grade numpy array.
I used a for loop, but since the first element is completed, it doesnt continue more.

import numpy as np
from scipy import stats

marks = np.array([90,72,82,90,69,19,23,30,45,5])

#Average of the array
avg = np.average(marks)


mdn = np.median(marks)

stand_dev = np.std(marks)

rang = np.ptp(marks)

mode = stats.mode(marks)

mode = mode[0]

# the loop that turns marks into letter Grade array
def letterGrade(mark):
    for i in range (len(mark)):
        list_new = []
        score = mark[i]
        if  score <= avg:
            return "F"
        elif (( score > avg) & ( score <= mdn)):
            return "D"
        elif (( score > mdn) & (score <= stand_dev)):
            return "C"
        elif (( score > stand_dev) & ( score <= rang)):
            return "B"
        elif (( score > rang) & ( score <= mode)):
            return "A"
        elif score > mode:
            return "A+"
    
    list_new.append(score)

letterGrade(marks)

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

This can be elegantly solved with digitize:

letters = np.array(['F', 'D', 'C', 'B', 'A', 'A+'])
bins = [avg, mdn, avg+stand_dev, rang, mode[0], 100]
letters[np.digitize(marks, bins, True)].tolist()

Result

['A', 'C', 'C', 'A', 'C', 'F', 'F', 'F', 'F', 'F']

(Note that I replaced stand_dev with avg+stand_dev so that it makes sense)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading