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
In [1]:
import pandas as pd
import numpy as np
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'])
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]: