UEFA_Euro_2020_Data / uefa_euro2020_processing.py
ForzaJuve1's picture
Upload uefa_euro2020_processing.py
9b78acf verified
raw
history blame
11.9 kB
# -*- coding: utf-8 -*-
"""UEFA_Euro2020_Processing.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/14eW1QiGXrszsqNFVKnT7WjDyDmxVuIve
"""
import pandas as pd
import numpy as np
from functools import reduce
match_events = pd.read_csv('/content/Match events.csv')
match_information = pd.read_csv('/content/Match information.csv')
match_line_up = pd.read_csv('/content/Match line-ups.csv')
match_player_stats = pd.read_csv('/content/player_stats.csv')
match_team_stats = pd.read_csv('/content/Match team statistics.csv')
pre_match_info = pd.read_csv('/content/Pre-match information.csv')
# impute the missing referee from CONMEBOL
match_information['RefereeWebName'] = match_information['RefereeWebName'].fillna("Rapallini")
# add columns that contain useful information for referee statistics
Euro2020_df = match_information.copy()
# add a stage variable to classify the matches
Euro2020_df.insert(loc=5, column = "Stage", value = np.where(Euro2020_df['MatchDay'] <= 3, 'Group Stage', 'Knockout Stage'))
# add varibles that contain useful statistics for referees
Euro2020_df.insert(loc=17, column='NumberofMatchesRefereedPostMatch',
value=Euro2020_df.groupby('RefereeWebName').cumcount().astype(int) + 1)
Euro2020_df.insert(loc=18, column='TotalNumberofMatchesRefereed',
value=Euro2020_df.groupby('RefereeWebName')['RefereeWebName'].transform('count').astype(int))
Euro2020_df.insert(loc=19, column = 'NumberofMatchesRefereedinGroupStage',
value = Euro2020_df.groupby('RefereeWebName')['Stage'].transform(lambda x: (x == 'Group Stage').sum()))
Euro2020_df.insert(loc=20, column = 'NumberofMatchesRefereedinKnockoutStage',
value = Euro2020_df.groupby('RefereeWebName')['Stage'].transform(lambda x: (x == 'Knockout Stage').sum()))
# create nested structures for match events
# Create a new DataFrame with only the columns needed for nesting
nested = match_events.iloc[:,[0] + list(range(3, 13))]
# Create another new df with only the separate columns
separate = match_events.iloc[:,0:3].drop_duplicates().set_index("MatchID")
# Group by 'MatchID' and 'Phase', create a nested structure for match events
nested_structure = (nested.groupby(['MatchID', 'Phase'])
.apply(lambda x: x.drop('MatchID', axis=1).to_dict('records'))
.reset_index(name='Events')
.pivot(index='MatchID', columns="Phase", values='Events'))
# Rename phases
phase_names = {
1: '1-First Half',
2: '2-Second Half',
3: '3-Extra Time First Half',
4: '4-Extra Time Second Half',
5: '5-Penalty Shootout'
}
nested_structure.rename(columns=phase_names, inplace=True)
# Combine the phase columns into one 'MatchEvent' column
nested_structure['MatchEvent'] = nested_structure.apply(lambda row: {phase: events for phase, events in row.items()}, axis=1)
# Drop the individual phase columns
nested_structure.drop(columns=phase_names.values(), inplace=True)
# Join the separate columns with the nested structure
nested_match_events = separate.join(nested_structure).reset_index()
nested_match_events = nested_match_events.drop(nested_match_events.columns[[1, 2]],axis=1)
# distinguish participants from the home and away teams in the line up dataset. Since only the pre_match_info
# df contains variables that distinguish home and away teams, need to combine both dfs and continue data processing.
line_up_merged = pd.merge(match_line_up, pre_match_info.iloc[:,[0,3,4,7]],
on=['MatchID','ID'], how='left')
# Create nested structures for the home and away team's line-ups in each match
# Variables for staff and players respectively
staff_vars = ['Country', 'ID', 'OfficialName', 'OfficialSurname', 'ShortName', 'Role']
player_vars = [col for col in line_up_merged.columns if col not in ['MatchID', 'HomeTeamName', 'AwayTeamName',
'IsPitch', 'IsBench', 'IsStaff', 'IsHomeTeam','IsAwayTeam']]
# Function to create nested structure for one team
def create_team_structure(x, is_home_team):
if is_home_team:
# Filter for home team players
squad_df = x[x['IsHomeTeam'] == True].copy()
else:
# Filter for away team players
squad_df = x[x['IsHomeTeam'] == False].copy()
# Starting 11
starting_11 = squad_df[squad_df['IsPitch']][player_vars]
# Benched players
benched_players = squad_df[squad_df['IsBench']][player_vars]
# Staff
staff = squad_df[squad_df['IsStaff']][staff_vars]
return {'Starting11': starting_11.to_dict('records'),
'Benched Players': benched_players.to_dict('records'),
'Staff': staff.to_dict('records')}
# Apply the function to each match for home and away teams
nested_line_up = line_up_merged.groupby('MatchID').apply(lambda line_up_merged: {
'HomeTeamLineUp': create_team_structure(line_up_merged, True),
'AwayTeamLineUp': create_team_structure(line_up_merged, False)
}).reset_index(name='TeamLineUps')
# create nested structures for team stats
# Firstly retrieve and classify all the team stats. Also explore the difference in elements of team stats
# player stats so that the classification on both could be easier.
team_unique = list(match_team_stats['StatsName'].unique())
print(team_unique)
player_unique = list(match_player_stats['StatsName'].unique())
print(player_unique)
set1 = set(team_unique)
set2 = set(player_unique)
# Find elements in list1 but not in list2
difference1 = set1 - set2
# Find elements in list2 but not in list1
difference2 = set2 - set1
# Convert the sets back to lists, if needed
diff_list1 = list(difference1)
diff_list2 = list(difference2)
print(diff_list1)
print(diff_list2)
# classify statistics
attacking = [team_unique[0]] + team_unique[2:8] + [team_unique[22]] + team_unique[24:56] + team_unique[58:74] + team_unique[93:106] + [team_unique[120]] + [team_unique[178]] + team_unique[182:184] + team_unique[186:189] + [team_unique[192]]
possession = [team_unique[1]] + team_unique[16:18] + [team_unique[56]] + team_unique[74:93] + team_unique[112:119]
violation_foul_discipline = [team_unique[8]] + team_unique[13:16] + team_unique[147:156]
goalkeeping = [team_unique[9]] + team_unique[125:146] + team_unique[189:191]
defending = team_unique[10:13] + [team_unique[21]] + [team_unique[23]] + team_unique[106:112] + [team_unique[119]] + team_unique[121:125]
coverage_speed = team_unique[18:21] + team_unique[156:169] + [team_unique[177]] + team_unique[179:181] + team_unique[184:186] + [team_unique[191]]
time_stats = [team_unique[57]] + [team_unique[146]] + team_unique[169:177]
matches_played = [team_unique[181]]
# check if the categories cover all team stats
set3 = set(attacking+possession+violation_foul_discipline+goalkeeping+defending+coverage_speed+time_stats+matches_played)
set4 = set(team_unique)
difff = list(set4-set3)
difff
# add unique stats for players to certain categories
player_time_stats = time_stats + [diff_list2[0]] + [diff_list2[2]] + [diff_list2[4]]
player_coverage_speed = coverage_speed + [diff_list2[1]] + [diff_list2[3]]
# assign category based on names for team stats
def assign_category(name):
if name in attacking:
return 'attacking'
elif name in possession:
return 'possession'
elif name in violation_foul_discipline:
return 'violation&foul&discipline'
elif name in goalkeeping:
return 'goalkeeping'
elif name in defending:
return 'defending'
elif name in coverage_speed or name in player_coverage_speed:
return 'coverage&speed'
elif name in time_stats or name in player_time_stats:
return 'time stats'
elif name in matches_played:
return 'matches played'
# Apply the function to create a new column 'Category' for both team stats and player stats
match_team_stats['StatsCategory'] = match_team_stats['StatsName'].apply(lambda name: assign_category(name))
match_player_stats['StatsCategory'] = match_player_stats['StatsName'].apply(lambda name: assign_category(name))
# create the nested structure for team stats
stats_details_cols = ['TeamID', 'TeamName', 'StatsID', 'StatsName', 'Value', 'Rank']
# Function to create nested stats by category
def nested_stats(group):
# Create nested structure for home and away team stats
home_stats = group[group['IsHomeTeam']]
away_stats = group[group['IsAwayTeam']]
# Function to create stats by category
def stats_by_category(team_stats):
return team_stats.groupby('StatsCategory')[stats_details_cols].apply(lambda x: x.to_dict('records')).to_dict()
# Create the nested stats dictionary
nested_stats_dict = {
'HomeTeamStats': stats_by_category(home_stats),
'AwayTeamStats': stats_by_category(away_stats)
}
return nested_stats_dict
# Group by 'MatchID' and apply the nested stats function
nested_team_stats = match_team_stats.groupby('MatchID').apply(nested_stats).reset_index(name='TeamStats')
# create the nested structure for player stats
player_stats_details = ['PlayerID', 'PlayerName', 'PlayerSurname', 'IsGoalkeeper', 'PlayedTime', 'StatsID', 'StatsName', 'Value', 'Rank']
pre_match = pre_match_info.copy()
pre_match.rename(columns={'ID': 'PlayerID'}, inplace=True)
player_stats_merged = pd.merge(match_player_stats, pre_match.iloc[:,[0,3,4,7]],
on=['MatchID','PlayerID'], how='left')
# Function to create nested stats by category
def nested_stats(group):
# Create nested structure for home and away team stats
home_stats = group[group['IsHomeTeam']]
away_stats = group[group['IsAwayTeam']]
# Function to create stats by category
def stats_by_category(player_stats):
return player_stats.groupby('StatsCategory')[player_stats_details].apply(lambda x: x.to_dict('records')).to_dict()
# Create the nested stats dictionary
nested_stats_dict = {
'HomeTeamPlayerStats': stats_by_category(home_stats),
'AwayTeamPlayerStats': stats_by_category(away_stats)
}
return nested_stats_dict
# Group by 'MatchID' and apply the nested stats function
nested_player_stats = player_stats_merged.groupby('MatchID').apply(nested_stats).reset_index(name='PlayerStats')
# create nested structure for pre match player info
players_info = pre_match[pre_match['IsStaff'] == False]
# Define the columns we want to include for each player
player_info_vars = ['PlayerID', 'OfficialName', 'OfficialSurname', 'JerseyName', 'ShortName', 'GoalScored', 'CleanSheet', 'SuspendedIfBooked', 'Role']
# Create nested structure
def create_player_structure(df, is_home_team):
# Filter for home or away team players
home_team_players = df[df['IsHomeTeam'] == is_home_team][player_info_vars]
# Create a list of dictionaries, one for each player
return home_team_players.to_dict('records')
# Construct the nested structure for the DataFrame
nested_structure = {
'MatchID': [],
'PlayerPreMatchInfo': []
}
for match_id, group in players_info.groupby('MatchID'):
nested_structure['MatchID'].append(match_id)
nested_structure['PlayerPreMatchInfo'].append({
'HomeTeamPlayerInfo': create_player_structure(group, True),
'AwayTeamPlayerInfo': create_player_structure(group, False)
})
# Convert the nested structure to a DataFrame
nested_player_pre_match_info = pd.DataFrame(nested_structure)
# merge all sub datasets with nested structures into the final df
all_dfs = [Euro2020_df,nested_match_events,nested_line_up,nested_team_stats,nested_player_stats,nested_player_pre_match_info]
# Using functools.reduce to merge all DataFrames
Euro2020_df_final = reduce(lambda left, right: pd.merge(left, right, on='MatchID', how='outer'), all_dfs)
Euro2020_df_final
Euro2020_df_final.to_csv('Euro2020.csv', index=False)
Euro2020_df_final.to_json('Euro2020.json', orient='records', lines=False)
Euro2020_df_final.to_parquet('Euro2020.parquet', index = False)