Soccer Through the Ages
  • AI Chat
  • Code
  • Report
  • Beta
    Spinner

    Soccer Through the Ages

    This dataset contains information on international soccer games throughout the years. It includes results of soccer games and information about the players who scored the goals. The dataset contains data from 1872 up to 2023.

    💾 The data

    • data/results.csv - CSV with results of soccer games between 1872 and 2023
      • home_score - The score of the home team, excluding penalty shootouts
      • away_score - The score of the away team, excluding penalty shootouts
      • tournament - The name of the tournament
      • city - The name of the city where the game was played
      • country - The name of the country where the game was played
      • neutral - Whether the game was played at a neutral venue or not
    • data/shootouts.csv - CSV with results of penalty shootouts in the soccer games
      • winner - The team that won the penalty shootout
    • data/goalscorers.csv - CSV with information on goal scorers of some of the soccer games in the results CSV
      • team - The team that scored the goal
      • scorer - The player who scored the goal
      • minute - The minute in the game when the goal was scored
      • own_goal - Whether it was an own goal or not
      • penalty - Whether the goal was scored as a penalty or not

    The following columns can be found in all datasets:

    • date - The date of the soccer game
    • home_team - The team that played at home
    • away_team - The team that played away

    These shared columns fully identify the game that was played and can be used to join data between the different CSV files.

    Source: GitHub

    📊 Some guiding questions and visualization to help you explore this data:

    1. Which are the 15 countries that have won the most games since 1960? Show them in a horizontal bar plot.
    2. How many goals are scored in total in each minute of the game? Show this in a bar plot, with the minutes on the x-axis. If you're up for the challenge, you could even create an animated Plotly plot that shows how the distribution has changed over the years.
    3. Which 10 players have scored the most hat-tricks?
    4. What is the proportion of games won by each team at home and away? What is the difference between the proportions?
    5. How many games have been won by the home team? And by the away team?

    💼 Develop a case study for your portfolio

    After exploring the data, you can create a comprehensive case study using this dataset. We have provided an example objective below, but feel free to come up with your own - the world is your oyster!

    Example objective: The UEFA Euro 2024 tournament is approaching. Utilize the historical data to construct a predictive model that forecasts potential outcomes of the tournament based on the team draws. Since the draws are not known yet, you should be able to configure them as variables in your notebook.

    # Imported all necessary frameworks
    import pandas as pd
    import matplotlib.pyplot as plt
    import seaborn as sns
    import numpy as np
    import datetime 
    import plotly.express as px
    
    
    
    
    # load all necessary dataset
    goalscorers = pd.read_csv('data/goalscorers.csv')
    results = pd.read_csv('data/results.csv')
    shootouts = pd.read_csv('data/shootouts.csv')
    results = results.merge(shootouts, how="left")
    
    # Created column with winners
    results['win'] = None
    
    results['win'] = np.where((results['home_score'] > results['away_score']) & 
                                                 (results['win'] != None) ,
                                                  results['home_team'], results['win'])
    
    results['win'] = np.where((results['home_score'] < results['away_score']) & 
                                                 (results['win'] != None),
                                                  results['away_team'], results['win'])
    
    results['win'] = np.where((results['home_score'] == results['away_score']) & 
                                                 (results['win'] != None),
                                                 pd.Series(["draw"]), results['win'])
    results['win'] = np.where((results['winner'].isin(results['home_team'])) | (results['winner'].isin(results['away_team'])) & (results['win'] == 'draw'), results['winner'], results['win'])
    
    # Converted date with string to datetime
    results["date"] = results['date'].apply(lambda x : datetime.datetime.strptime(x, '%Y-%m-%d'))

    1.The 15 countries that have won the most games since 1960

    # Created dataset with winners since 1960
    results_since_1960 = results[results["date"] >= datetime.datetime.strptime('1960-01-01', '%Y-%m-%d')]
    won_since_1960 = results_since_1960['win'].value_counts().drop(index='draw').head(15)
    won_since_1960 = pd.DataFrame(won_since_1960).reset_index(names='country')
    sns.set_theme(style="whitegrid")
    sns.barplot(won_since_1960, x='win', y='country').set(title='The 15 countries that have won the most games since 1960')
    
    
    # Converted date with string to datetime
    goalscorers['date'] = goalscorers['date'].apply(lambda x : datetime.datetime.strptime(x, '%Y-%m-%d'))
    goalscorers['year'] = goalscorers['date'].dt.strftime('%Y')
    
    # Created df with minutes and goals
    minute_goals = goalscorers[['minute']].groupby(['minute']).size()
    
    # Built barplot 
    plt.figure(figsize=(20, 6))
    plt.xticks(rotation=90)
    sns.barplot(goalscorers, x=minute_goals.index, y=minute_goals.values)
    plt.xlabel('Minute')
    plt.ylabel('Total Goals')
    plt.title('Total Goals Scored in Each Minute of the Game')
    plt.show()
    
    
    
    # Group the data by year and minute and calculate the total goals
    minute_goals = goalscorers[['year', 'minute']].groupby(['year','minute']).size().reset_index(name='total_goals')
    
    # Create an animated bar plot
    fig = px.bar(minute_goals, x='minute', y='total_goals', animation_frame='year', range_x=[0, 122], range_y=[0, 100],
                     labels={'minute': 'Minute', 'total_goals': 'Total Goals'},
                     title='Distribution of Goals Over the Years')
    # Show the plot
    fig.show()
    
    # The number of goals scored by each football player is calculated
    goals = goalscorers[['date', 'scorer']].groupby(['date', 'scorer']).size().reset_index(name='goals')
    # The number of hat trick by each football player
    hat_trick_count = goals[goals['goals'] >= 3][['scorer', 'goals']].groupby('scorer').size().reset_index(name='hat_trick')
    hat_trick_count = hat_trick_count.sort_values('hat_trick', ascending=False).head(10)
    
    # 10 players with the most hat-tricks per country
    plt.figure(figsize=(12, 6))
    sns.barplot(data=hat_trick_count, x='hat_trick', y='scorer')
    plt.xlabel('Number of Hat-tricks')
    plt.ylabel('Player')
    plt.title('Top 10 Players with the Most Hat-tricks')
    plt.show()
    
    
    # Home wins counted per each country
    home_wins_per_country = results[results['win'] == results['home_team']]['home_team'].value_counts() / results['home_team'].value_counts()
    
    # Away  wins counted per each country
    away_wins_per_country = results[results['win'] == results['away_team']]['away_team'].value_counts() / results['away_team'].value_counts()
    
    # Countries that have never won at home or away are set to 0
    home_wins_per_country = home_wins_per_country.fillna(0)
    away_wins_per_country = away_wins_per_country.fillna(0)
    # Difference between home wins and away wins per each country
    difference = home_wins_per_country - away_wins_per_country
    ‌
    ‌
    ‌