Title: Create A Pandas Column With A For Loop
Slug: pandas_create_column_with_loop
Summary: Create A Pandas Column With A For Loop
Date: 2016-05-01 12:00
Category: Python
Tags: Data Wrangling
Authors: Chris Albon

Preliminaries


In [1]:
import pandas as pd
import numpy as np

Create an example dataframe


In [2]:
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


In [3]:
# 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

In [4]:
# View the new dataframe
df


Out[4]:
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