text_html_output_1.png application_vnd.jupyter.stderr_output_1.png
import numpy as np

import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)

import trueskill as ts

def cleanResults(numRaces, dfResults):
    for raceCol in range(1, numRaces + 1):
        dfResults['R' + str(raceCol)] = dfResults['R' + str(raceCol)].str.replace('\\(|\\)|DNF-|RET-|SCP-|RDG-|RCT-|DNS-[0-9]*|DNC-[0-9]*|OCS-[0-9]*', '')
        dfResults['R' + str(raceCol)] = pd.to_numeric(dfResults['R' + str(raceCol)])
    return dfResults

def doRating(numRaces, dfResults, dfRatings):
    for raceCol in range(1, numRaces + 1):
        competed = dfRatings['Name'].isin(dfResults['Name'][dfResults['R' + str(raceCol)].notnull()])
        rating_group = list(zip(dfRatings['Rating'][competed].T.values.tolist()))
        dfRatings['Rating'][competed] = ts.rate(rating_group, ranks=dfResults['R' + str(raceCol)][competed].T.values.tolist())
    return pd.DataFrame(dfRatings)

dfResults = pd.read_csv('../input/201608-SanFracisco-HydrofoilProTour.csv')
dfResults = cleanResults(16, dfResults)
dfRatings = pd.DataFrame()
dfRatings['Name'] = dfResults['Name']
dfRatings['Rating'] = pd.Series(np.repeat(ts.Rating(), len(dfRatings))).T.values.tolist()
dfRatings = doRating(16, dfResults, dfRatings)
dfRatings['mu'] = pd.Series(np.repeat(25.0, len(dfRatings)))
dfRatings['sigma'] = pd.Series(np.repeat(8.333, len(dfRatings)))
dfRatings['mu_minus_3sigma'] = pd.Series(np.repeat(0.0, len(dfRatings)))
for i in range(0, len(dfRatings['Rating'])):
    dfRatings['mu'][i] = float(dfRatings['Rating'][i].mu)
    dfRatings['sigma'][i] = float(dfRatings['Rating'][i].sigma)
    dfRatings['mu_minus_3sigma'][i] = float(dfRatings['mu'][i] - 3 * dfRatings['sigma'][i])

dfRatings.index = dfRatings['mu_minus_3sigma'].rank(ascending=False)
dfRatings.sort('mu_minus_3sigma', ascending=False)