This project serves as a comprehensive guide to performing football analysis using Python. You can view Live Demo :
Data Analysis Football Project Using Python
This project serves as a comprehensive guide to performing football analysis using Python. It covers data collection, cleaning, manipulation, and visualization to gain insights into football data.
Live Project Demo
You can view my live project demo: https://youtu.be/_7Q9iiH2A10
Requirements
To successfully run this project, you will need the following:
- Python 3.x
- Jupyter Notebook
- Pandas
- Numpy
- Matplotlib
- Seaborn
Installation
To get started, follow these installation steps:
- Install Python 3.x from the official website.
- Open the Command Prompt terminal.
- Type
python --versionto check if Python is already installed and if it is, verify that the version is up-to-date. - Verify the preferred installer program,
pip, by typingpip --version. - Install Jupyterlab by running
pip install jupyterlabin the Command Prompt terminal. - Install Jupyter Notebook by running
pip install jupyter notebookin the Command Prompt terminal. - Once Jupyter Notebook has finished downloading, you will see the file path location in the terminal. Copy this path file location and paste it on a new line, and then hit enter. In my case, the file path is:
C:\Users\ayans\AppData\Local\Programs\Python\Python310\python.exe -m pip install --upgrade pip - Install the necessary packages by running
pip install pandas,pip install numpy,pip install matplotlib, andpip install seabornin the Command Prompt terminal. - Create a folder on your desktop for this project. For example:

- Once you have created the desktop folder, open the folder and copy the folder path location. In my case, the folder path location is:
C:\Users\ayans\Desktop\Test_Jupyter - Paste the folder path location into the Command Prompt terminal by typing
cd C:\Users\ayans\Desktop\Test_Jupyter - After pasting the folder path location, the path will change to:

- Type
jupyter notebookand hit enter. You will see a new tab open in your browser displaying the Jupyter Notebook dashboard. - Click on the following options to get started, as shown in the image below:

Jupyter Notebook - Python Programming
To begin football data analysis with Python, follow these steps:
Step 1:
# Import Librarirs
import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns %matplotlib inline
Step 2:
# Load EPL data into a DataFrame
epldf = pd.readcsv('C:\\Users\\ayans\\Downloads\\EPL2021\\EPL2021.csv') epl_df.head()
Step 3:
# Print a summary of the DataFrame
epl_df.info()
Step 4:
# Print summary statistics of the DataFrame
epl_df.describe()
Step 5:
# Count the number of missing values (NaN) in each column of epl_df
epl_df.isna().sum()
Step 6:
# Create 2 new columns
epldf['MinsPerMatch'] = (epldf['Mins'] / epl_df['Matches']).astype(int) epldf['GoalsPerMatch'] = (epldf['Goals'] / epl_df['Matches']).astype(float) epl_df.head()
Step 7:
# Total Goals
TotalGoals = epldf['Goals'].sum() print(Total_Goals)
Step 8:
# Penalty Goals
TotalPenaltyGoals = epldf['Penalty_Goals'].sum() print(Total_PenaltyGoals)
Step 9:
# Penalty Attempts
TotalPenaltyAttempts = epldf['Penalty_Attempted'].sum() print(Total_PenaltyAttempts)
Step 10:
# Pie chart for penalties missed vs scored
plt.figure(figsize = (13, 6)) plnotscored = epldf['PenaltyAttempted'].sum() - Total_PenaltyGoals data = [plnotscored, Total_PenaltyGoals] labels = ['Penalties Missed', 'Penalty Scored'] colorpalette = sns.colorpalette("Paired") plt.pie(data, labels = labels, colors = color_palette, autopct = '%.0f%%') plt.show()
Step 11:
# Unique positions
epl_df['Position'].unique()
Step 12:
# Total FW Players
epldf[epldf['Position'] == 'FW']
Step 13:
# Players from different nations
np.size((epl_df['Nationality'].unique()))
Step 14:
# Most players from which countries
nationality = epldf.groupby('Nationality').size().sortvalues(ascending = False) nationality.head(10).plot(kind = 'bar', figsize = (12, 6), color = sns.color_palette('magma'))
Step 15:
# Clubs with maximum players in their squad
epldf['Club'].valuecounts().nlargest(5).plot(kind = 'bar', color = sns.color_palette("viridis"))
Step 16:
# Clubs with latest players in their squad
epldf['Club'].valuecounts().nsmallest(5).plot(kind = 'bar', color = sns.color_palette("viridis"))
Step 17:
# Players based on age group
Under20 = epldf[epldf['Age'] <= 20] age2025 = epldf[(epldf['Age'] > 20) & (epldf['Age'] <= 25)] age2530 = epldf[(epldf['Age'] > 25) & (epldf['Age'] <= 30)] Above30 = epldf[epldf['Age'] > 30]
Step 18:
# Assuming the following DataFrame exist: Under20, age2025, age2530 and Above30
x = np.array([Under20['Name'].count(),age2025['Name'].count(),age2530['Name'].count(),Above30['Name'].count()]) mylabels = ["<=20", ">20 & <=25", ">25 & <=30", ">30"] plt.title('Total Players with Age Groups', fontsize=20) plt.pie(x, labels=mylabels, autopct = "%.1f%%") plt.show()
Step 19:
# Total under 20 players in each club
playersunder20 = epldf[epldf['Age'] < 20] playersunder20['Club'].valuecounts().plot(kind = 'bar', color = sns.colorpalette("cubehelix"))
Step 20:
# Under 20 players in Manu
playersunder20[playersunder20["Club"] == 'Manchester United']
Step 21:
# Under 20 players in Chelsea
playersunder20[playersunder20["Club"] == 'Chelsea']
Step 22:
# Average age of players in each club
plt.figure(figsize = (12, 6)) sns.boxplot(x = 'Club', y = 'Age', data = epl_df) plt.xticks(rotation = 90)
Step 23:
# Group the English Premier League DataFrame (epl_df) by club and count the number of players in each club
numplayer = epldf.groupby('Club').size() data = (epldf.groupby('Club')['Age'].sum()) / numplayer data.sort_values(ascending = False)
Step 24:
# Total assists from each club
Assitsbyclub = pd.DataFrame(epldf.groupby('Club', asindex = False)['Assists'].sum()) sns.settheme(style = "whitegrid", colorcodes = True) ax = sns.barplot(x = 'Club', y = 'Assists', data = Assitsbyclub.sort_values(by = 'Assists'), palette = 'tab20') ax.set_xlabel("Club", fontsize = 30) ax.set_ylabel("Assists", fontsize = 20) plt.xticks(rotation = 75) plt.rcParams["figure.figsize"] = (20, 8) plt.title('Plot of Club vs Total Assists', fontsize = 20)
Step 25:
# Top 10 Assists
top10assists = epl_df[['Name', 'Club', 'Assists', 'Matches']].nlargest(n = 10, columns = 'Assists') top10assists
Step 26:
# Creating a DataFrame to group the total goals scored by each club
Goalsbyclubs = pd.DataFrame(epldf.groupby('Club', asindex = False)['Goals'].sum()) sns.settheme(style ="whitegrid", colorcodes = True) ax = sns.barplot(x = 'Club', y = 'Goals', data = Goalsbyclubs.sort_values(by ="Goals"), palette = 'rocket') ax.set_xlabel("Club", fontsize = 30) ax.set_ylabel("Goals", fontsize = 20) plt.xticks(rotation =75) plt.rcParams["figure.figsize"] = (20, 8) plt.title('Plot of Club vs Total Goals', fontsize = 20)
Step 27:
# Most goals by players
top10goals = epl_df[['Name', 'Club', 'Goals', 'Matches']].nlargest(n = 10, columns = 'Goals') top10goals
Step 28:
# Goals per match
top10goalspermatch = epl_df[['Name', 'GoalsPerMatch', 'Matches', 'Goals']].nlargest(n = 10, columns = 'GoalsPerMatch') top10goalspermatch
Step 29:
# Pie Chart - Goals with assist and without assist
plt.figure(figsize = (14, 7)) assists = epl_df['Assists'].sum() data = [Total_Goals - assists, assists] labels = ['Goals without assists', 'Goals with assists'] color = sns.color_palette('Set2') plt.pie(data, labels = labels, colors = color, autopct ='%.0f%%') plt.title('Percentage of Goals with Assists', fontsize = 20) plt.show()
Step 30:
# Top 10 players with most yellow cards
eplyellow = epldf.sortvalues(by = 'YellowCards', ascending = False)[:10] plt.figure(figsize = (20, 6)) plt.title("Players with the most yellow cards") c = sns.barplot(x = eplyellow['Name'], y = eplyellow['Yellow_Cards'], label = 'Players', color ='yellow') plt.ylabel('Number of Yellow Cards') c.setxticklabels(c.getxticklabels(), rotation = 45) plt.show()
Data Visualization
Finally, we will visualize the data to make it more accessible and understandable. This includes creating plots, charts, and graphs.
Conclusion
This project provides a comprehensive guide to performing data analysis football using Python. By following these steps, you will be able to collect, clean, manipulate, and visualize football data. Enjoy exploring the world of football data analytics!