<jupyter_start><jupyter_text>EDA on FIFA World Cup Matches Dataset: https://www.kaggle.com/abecklas/fifa-world-cup<jupyter_code>import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
%matplotlib inline
import plotly as py
import cufflinks as cf
from plotly.offline import iplot
py.offline.init_notebook_mode(connected=True)
cf.go_offline()<jupyter_output><empty_output><jupyter_text>Upload the data<jupyter_code>world_cups = pd.read_csv('WorldCups.csv')
players = pd.read_csv('WorldCupPlayers.csv')
matches = pd.read_csv('WorldCupMatches.csv')
world_cups.head()
players.head()
matches.head()
matches.tail()
world_cups['Country'].unique() , len(world_cups['Country'].unique()) # finding unique name of Country and total number<jupyter_output><empty_output><jupyter_text>Data Cleaning<jupyter_code>matches.dropna(subset=['Year'], inplace=True)
matches.tail()
matches['Home Team Name'].value_counts()
names = matches[matches['Home Team Name'].str.contains('rn">')]['Home Team Name'].value_counts() # finding the 'Home Team Name'
                                                                                                 # that havr 'rn' written in it and taking value count of it
names
names.index
wrong = list(names.index) # list containing wrong names
wrong
correct = [name.split('>')[1] for name in wrong] # splitting the list into 2, one contaning '>' and another contaning correct names
correct
old = ['Germany FR', 'Maracan� - Est�dio Jornalista M�rio Filho', 'Estadio do Maracana'] # wrong name
new = ['Germany', 'Maracanã Stadium', 'Maracanã Stadium'] # correct name
wrong = wrong + old
correct = correct + new
wrong, correct
for index, wr in enumerate(wrong): #this is the word in enumerate, here enumerate so that it can iterate over this list 
                                    #and it will also produce the index of that list on which it is iterate.

    world_cups = world_cups.replace(wrong[index], correct[index]) # replace wrong with correct ones
    
for index, wr in enumerate(wrong):
    matches = matches.replace(wrong[index], correct[index]) # replace wrong with correct ones
    
for index, wr in enumerate(wrong):
    players = players.replace(wrong[index], correct[index]) # replace wrong with correct ones
    
names = matches[matches['Home Team Name'].str.contains('rn">')]['Home Team Name'].value_counts() # finding the 'Home Team Name'
                                                                                                 # that havr 'rn' written in it and taking value count of it
names<jupyter_output><empty_output><jupyter_text>Most Number of World Cup Winning Title<jupyter_code>winner = world_cups['Winner'].value_counts() # winner list with winning count
winner
runnerup = world_cups['Runners-Up'].value_counts() # Runners-Up list
runnerup 
third = world_cups['Third'].value_counts() # third place list
third
teams = pd.concat([winner, runnerup, third], axis = 1) # concate 'winner', 'runnerup', 'third' to new dataframe 'teams'
teams.fillna(0, inplace = True) # fill na values
teams = teams.astype(int) # converting to integer values
teams
teams.iplot(kind = 'bar', xTitle = 'Teams', yTitle = 'Count', title = 'FIFA World Cup Winning Count')<jupyter_output><empty_output><jupyter_text>Number of Goal Per Country<jupyter_code>matches.head(2)
home = matches[['Home Team Name', 'Home Team Goals']].dropna() # creating a new dataframe 'home' from 'Home Team Name', 'Home Team Goals' and droping NA values
away = matches[['Away Team Name', 'Away Team Goals']].dropna() # creating a new dataframe 'away' from 'Away Team Name', 'Away Team Goals' and droping NA values
home.columns = ['Countries', 'Goals'] #renaming colomns
away.columns = home.columns
goals = home.append(away, ignore_index=True) # append 'away' in new dataframe 'goals'
goals = goals.groupby('Countries').sum() # grouping dataframe with country names and showing the goals sum count
goals
goals = goals.sort_values(by = 'Goals', ascending=False) # sorting in ascending
goals
#plot top 20 names
goals[:20].iplot(kind = 'bar', xTitle = 'Country Names', yTitle = 'Goals', title = 'Countries Hits Most Number of Goals')<jupyter_output><empty_output><jupyter_text>Attendance, Number of Teams, Goals, and Matches per Cup<jupyter_code>world_cups.head(1)
world_cups['Attendance'] = world_cups['Attendance'].str.replace(".", "") # removing '.'
world_cups.head(1)
fig, ax = plt.subplots(figsize = (10, 5))
sns.despine(right = True)
g = sns.barplot(x = 'Year', y = 'Attendance', data = world_cups)
g.set_xticklabels(g.get_xticklabels(), rotation = 80)
g.set_title('Attendance per Year')

#======================
fig, ax = plt.subplots(figsize = (10, 5))
sns.despine(right = True)
g = sns.barplot(x = 'Year', y = 'QualifiedTeams', data = world_cups)
g.set_xticklabels(g.get_xticklabels(), rotation = 80)
g.set_title('Qualified Teams per Year')

#======================
fig, ax = plt.subplots(figsize = (10, 5))
sns.despine(right = True)
g = sns.barplot(x = 'Year', y = 'GoalsScored', data = world_cups)
g.set_xticklabels(g.get_xticklabels(), rotation = 80)
g.set_title('Goals Scored by Teams per Year')

#======================
fig, ax = plt.subplots(figsize = (10, 5))
sns.despine(right = True)
g = sns.barplot(x = 'Year', y = 'MatchesPlayed', data = world_cups)
g.set_xticklabels(g.get_xticklabels(), rotation = 80)
g.set_title('Matches Played by Teams per Year')



plt.show()<jupyter_output>C:\Users\ritesh\AppData\Local\Temp/ipykernel_6268/4081762660.py:4: UserWarning:

FixedFormatter should only be used together with FixedLocator<jupyter_text>Goals Per Team Per Word Cup<jupyter_code>matches.head(1)
home = matches.groupby(['Year', 'Home Team Name'])['Home Team Goals'].sum() # groupby 'Year', 'Home Team Name' and sum by 'Home Team Name'
home
away = matches.groupby(['Year', 'Away Team Name'])['Away Team Goals'].sum() # groupby 'Year', 'Away Team Name' and sum by'Away Team Goals'
away
goals = pd.concat([home, away], axis = 1) # concat 'home', 'away' to new dataframe 'goals'
goals.fillna(0, inplace = True) # fill NA values with '0'
goals['Goals'] = goals['Home Team Goals'] + goals['Away Team Goals']
goals = goals.drop(labels = ['Home Team Goals', 'Away Team Goals'], axis = 1) # drop colomns 'Home Team Goals' and 'Away Team Goals'
goals
goals = goals.reset_index()
goals.columns = ['Year', 'Country', 'Goals'] # giving colomns new names
goals = goals.sort_values(by = ['Year', 'Goals'], ascending=[True, False]) # sorting by 'year' and 'goal' 
goals
top5 = goals.groupby('Year').head(5) # top 5 countries. group by year so we get each years top 5 countries
top5.head(10)
import plotly.graph_objects as go
x, y = goals['Year'].values, goals['Goals'].values
data = []

for team in top5['Country'].drop_duplicates().values:
    year = top5[top5['Country'] == team]['Year']
    goal = top5[top5['Country'] == team]['Goals']
    
    data.append(go.Bar(x = year, y = goal, name = team))
    
layout = go.Layout(barmode = 'stack', title = 'Top 5 Teams with Most Goals', showlegend = False)

fig = go.Figure(data = data, layout = layout)
fig.show()<jupyter_output><empty_output><jupyter_text>Matches with Highest Number of Attendance<jupyter_code>matches.head(1)
matches['Datetime'] = pd.to_datetime(matches['Datetime']) #changing to date time formate
matches.head(1)
matches['Datetime'] = matches['Datetime'].apply(lambda x: x.strftime('%d %b, %Y'))
matches.head(1)
top10 = matches.sort_values(by = 'Attendance', ascending = False)[:10]
top10['vs'] = top10['Home Team Name'] + " vs " + top10['Away Team Name']

plt.figure(figsize = (12, 9))

ax = sns.barplot(y = top10['vs'], x = top10['Attendance'])
sns.despine(right = True)

plt.ylabel('Match Teams')
plt.xlabel('Attendance')
plt.title('Matches with the highest number of attendance')

## now writting stadium names and date inside the plot
for i, s in enumerate("Stadium: " + top10['Stadium'] + ", Date: " + top10['Datetime']):
    ax.text(2000, i, s, fontsize = 12, color = 'white')

plt.show()<jupyter_output><empty_output><jupyter_text>Stadiums with Highest Average Attendance<jupyter_code>matches['Year'] = matches['Year'].astype(int)

std = matches.groupby(['Stadium', 'City'])['Attendance'].mean().reset_index().sort_values(by = 'Attendance', ascending = False)

top10 = std[:10]


plt.figure(figsize= (12, 9))
ax = sns.barplot(y = top10['Stadium'], x = top10['Attendance'])
sns.despine(right = True)

plt.ylabel('Stadium Names')
plt.xlabel('Attendance')
plt.title('Stadium with the highest number of attendance')

# now writting city names inside the plot
for i, s in enumerate("City: " + top10['City']):
    ax.text(2000, i, s, fontsize = 12, color = 'white')

plt.show()
matches['City'].value_counts()[:20].iplot(kind = 'bar')<jupyter_output><empty_output><jupyter_text>Match outcomes by home and away teams<jupyter_code>def get_labels(matches):
    if matches['Home Team Goals'] > matches['Away Team Goals']:
        return 'Home Team Win'
    if matches['Home Team Goals'] < matches['Away Team Goals']:
        return 'Away Team Win'
    return 'DRAW'
matches['outcomes'] = matches.apply(lambda x: get_labels(x), axis = 1)
matches.head()
mt = matches['outcomes'].value_counts()
mt
plt.figure(figsize = (6, 6))

mt.plot.pie(autopct = "%1.0f%%", colors = sns.color_palette('winter_r'), shadow = True)

c = plt.Circle((0, 0), 0.4, color = 'white')
plt.gca().add_artist(c)
plt.title('Match Outcomes by Home and Away Teams')
plt.show()
import cufflinks
cufflinks.__version__<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.1505466778805719, 'fraction_numerical': 0.013036164844407064, 'mean_word_length': 4.953066332916145, 'pattern_counts': {'":': 0, '<': 41, '<?xml version=': 0, '>': 45, 'https://': 1, 'lorem ipsum': 0, 'www.': 1, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 10, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '10', 'dir': 'jupyter-structured-clean-dedup', 'id': '610118', 'license': 'MIT', 'n_tokens_mistral': 3313, 'n_tokens_neox': 3172, 'n_words': 891, 'path': '3 EDA on FIFA World Cup Matches/EDA on FIFA World Cup Matches.ipynb', 'repo_name': 'RIT-MESH/Machine-learning-projects', 'size': '9512'}