v Create A Pandas Column With A For Loop - Python

Create A Pandas Column With A For Loop

Preliminaries

import pandas as pd
import numpy as np

Create an example dataframe

raw_data = {'student_name': ['Miller', 'Jacobson', 'Ali', 'Milner', 'Cooze', 'Jacon', 'Ryaner', 'Sone', 'Sloan', 'Piger', 'Riani', 'Ali'], 
        'test_score': [76, 88, 84, 67, 53, 96, 64, 91, 77, 73, 52, np.NaN]}
df = pd.DataFrame(raw_data, columns = ['student_name', 'test_score'])

Create a function to assign letter grades

# Create a list to store the data
grades = []

# For each row in the column,
for row in df['test_score']:
    # if more than a value,
    if row > 95:
        # Append a letter grade
        grades.append('A')
    # else, if more than a value,
    elif row > 90:
        # Append a letter grade
        grades.append('A-')
    # else, if more than a value,
    elif row > 85:
        # Append a letter grade
        grades.append('B')
    # else, if more than a value,
    elif row > 80:
        # Append a letter grade
        grades.append('B-')
    # else, if more than a value,
    elif row > 75:
        # Append a letter grade
        grades.append('C')
    # else, if more than a value,
    elif row > 70:
        # Append a letter grade
        grades.append('C-')
    # else, if more than a value,
    elif row > 65:
        # Append a letter grade
        grades.append('D')
    # else, if more than a value,
    elif row > 60:
        # Append a letter grade
        grades.append('D-')
    # otherwise,
    else:
        # Append a failing grade
        grades.append('Failed')

# Create a column from the list
df['grades'] = grades
# View the new dataframe
df
student_name test_score grades
0 Miller 76.0 C
1 Jacobson 88.0 B
2 Ali 84.0 B-
3 Milner 67.0 D
4 Cooze 53.0 Failed
5 Jacon 96.0 A
6 Ryaner 64.0 D-
7 Sone 91.0 A-
8 Sloan 77.0 C
9 Piger 73.0 C-
10 Riani 52.0 Failed
11 Ali NaN Failed