Pandas: modify values in a column
Date: April 1st 2016
Last updated: April 1st 2016
Prepare data (use pd.read_sql)
import MySQLdb
import pandas as pd
db = MySQLdb.connect(host='localhost',user='duck',passwd='password',db='surfdiary')
df_mysql = pd.read_sql("""SELECT boardperformance,
boardlength,
boardwidth,
boardthickness,
boardvolume FROM surferprofile_board;""",
con = db)
Head of dataframe
# boardperformance boardlength boardwidth boardthickness boardvolume
#0 HP 5 10 18 3/8 2 3/16 24.69
#1 HP 6 0 18 5/8 2 5/16 27.17
#2 HP 6 2 18 3/4 2 3/8 28.25
#...
Access column data
df_mysql['boardvolume']
Modify values in a column
See convert string fraction to decimal for more info on the two functions used below (e.g. convert_feet_to_float).
from fractions import Fraction
df_mysql['boardlength'] = df_mysql['boardlength'].apply(convert_feet_to_float)
df_mysql['boardwidth'] = df_mysql['boardwidth'].apply(convert_my_string_to_float)
df_mysql['boardthickness'] = df_mysql['boardthickness'].apply(convert_my_string_to_float)
Head of dataframe
# boardperformance boardlength boardwidth boardthickness boardvolume
#0 HP 5.833333 18.3750 2.187500 24.69
#1 HP 6.000000 18.6250 2.312500 27.17
#2 HP 6.166667 18.7500 2.375000 28.25
#...