To compute a stable Elo rating for players based on a list of games in a dataframe, you can use the Elo rating system. Here's a Python code implementation to achieve that:
import pandas as pd
import math
# Initialize players' rating dictionary
players_ratings = {}
# Function to compute expected outcome using Elo formula
def expected_outcome(player_rating, opponent_rating):
return 1 / (1 + math.pow(10, (opponent_rating - player_rating) / 400))
# Function to update player ratings based on game outcome
def update_ratings(player, opponent, outcome, k_factor=32):
# Get initial ratings of player and opponent, default to 1000 if not found
player_rating = players_ratings.get(player, 1000)
opponent_rating = players_ratings.get(opponent, 1000)
# Compute expected outcome
expected = expected_outcome(player_rating, opponent_rating)
# Update player and opponent ratings
player_rating += k_factor * (outcome - expected)
opponent_rating += k_factor * ((1 - outcome) - (1 - expected))
# Store updated ratings in players_ratings dictionary
players_ratings[player] = player_rating
players_ratings[opponent] = opponent_rating
# Example dataframe of games with columns: player1, player2, outcome (1: win, 0: loss)
games_df = pd.DataFrame({
'player1': ['A', 'B', 'C', 'D', 'E', 'F'],
'player2': ['B', 'C', 'D', 'E', 'F', 'A'],
'outcome': [1, 0, 0, 1, 1, 0]
})
# Iterate over each game and update player ratings
for index, game in games_df.iterrows():
player1 = game['player1']
player2 = game['player2']
outcome = game['outcome']
update_ratings(player1, player2, outcome)
# Print the final ratings of players
for player, rating in players_ratings.items():
print(f"{player}: {rating}")
This code initializes an empty dictionary players_ratings to store the ratings of players. Then, it defines two functions: expected_outcome to compute the expected outcome using the Elo formula, and update_ratings to update the ratings of players based on game outcomes.
The code then defines an example dataframe `games_df