#----- EDA Libraries -------
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import plotly.express as px
import missingno as mn
import warnings
warnings.filterwarnings("ignore")
from IPython.display import Image
Image(filename='../input/fifa-pic/Ronaldo-copertina.jpg', height='50',width='800')
"""
# Contents
- Data CLeaning
- Visualisation
- Barplots
- Histograms
- PieChart
- Scatter Plot
- Radar Plot
"""
# Loading the data
data = pd.read_csv('../input/fifa19/data.csv')
data.head()
"""
### Step 1 Data Cleaning
"""
# Dropping some of the features

data.drop(['Unnamed: 0','ID','Photo','Flag','Club Logo'],axis = 1, inplace = True)
data.head()
# Size of the data
data.shape
data.columns
# Missing values
round(100*(data.isnull().sum()/len(data)),2)[:50]
# Missing values
round(100*(data.isnull().sum()/len(data)),2)[50:]
# We will drop all the rows having less than or equal to 10 percent missing values
var1 = [ 'LS', 'ST', 'RS', 'LW',
       'LF', 'CF', 'RF', 'RW', 'LAM', 'CAM', 'RAM', 'LM', 'LCM', 'CM', 'RCM',
       'RM', 'LWB', 'LDM', 'CDM', 'RDM', 'RWB', 'LB', 'LCB', 'CB', 'RCB', 'RB']
data.dropna(axis = 0, subset= var1,inplace = True)
data['ST']
round(100*(data.isnull().sum()/len(data)),2)[:50]
round(100*(data.isnull().sum()/len(data)),2)[50:]
var2 = ['Club','Contract Valid Until','Release Clause','Joined']
data.dropna(axis = 0 , subset=var2,inplace = True)
# Dropping the entire column of Loaned From as it has 93 percent approx missing values
data.drop(['Loaned From'],axis = 1,inplace = True)
# Checking for any missing value in the data
data.isnull().sum().any()
# Shape after removing rows and columns
data.shape
data.columns
"""
### Step 2 EDA

- Taking one feature at a time

#### Visualising using barplot
"""
nation_10_player = data['Nationality'].value_counts()[:11]
nation_10_player.plot.bar()
plt.title('Top 10 countries with most number of players in FIFA')
plt.xlabel('Country')
plt.ylabel('Number of players')
# Top 20 countries with the most young players
nation_10_age = data.groupby(['Nationality'])['Age'].mean().sort_values(ascending = True)[:20]
nation_10_age.plot.bar(figsize = (15,12))
plt.title('Top 20 countries with most young players')
plt.xlabel('Country')
plt.ylabel('Age')
# Top 11 players under 25 years of age with best 'Overall' 
young_best_overall = data[data['Age'] <= 25][:12]
young_best_overall[['Name','Overall','Age']]
plt.figure(figsize=(15,12))
plt.title('Player under 25 years of age with best Overall rating')
ax = sns.barplot(x = 'Name' , y = 'Overall', data = young_best_overall)

# Top 10 teams to pick if your playing a crucial match
top_club_potential = data.groupby('Club')['Potential'].mean().sort_values(ascending = False)[:11]
top_club_potential.plot.bar()
plt.xlabel('Club')
plt.ylabel('Potential')
# Using the following function to convert the 'Value' feature from 'object' dtype to 'int' dtype
def get_value(x):
    float_value = float(x[1:-1])
    if x[-1] == 'M':
        float_value = float_value * 1000000
    elif x[-1] == 'K':
        float_value = float_value * 1000
    else:
        float_value == 0
    return float_value    
data.Value = data.Value.apply(get_value)          
# Converting the dype from 'Float' to 'int'
data.Value = data.Value.astype('int64')
# After conversion
data.Value
# Top 10 most expensive players
top_exp_player = data[['Name','Value']].sort_values(by = 'Value', ascending = False)[:11]
top_exp_player
plt.figure(figsize=(15,8))
sns.barplot(x = top_exp_player['Name'], y = top_exp_player['Value'], data = top_exp_player)
plt.title('Top 10 most expensive players')
data.Wage
# Using the following function to convert the 'Wage' feature from 'object' dtype to 'int' dtype
def get_value(x):
    float_value = int(x[1:-1])
    if x[-1] == 'K':
        int_value = float_value * 1000
    else:
        int_value == 0
    return int_value    
data.Wage = data.Wage.apply(get_value) 
# Top 10 most highly paid players
top_paid_player = data[['Name','Wage']].sort_values(by = 'Wage', ascending = False)[:11]
top_paid_player
plt.figure(figsize=(15,8))
sns.barplot(x = top_paid_player['Name'], y = top_paid_player['Wage'], data = top_paid_player)
plt.title('Top 10 most paid players')
# Top 10 nation that pays their players well
top_paid_nation = data.groupby(['Nationality'])['Wage'].mean().sort_values(ascending = False)[:11]
top_paid_nation.plot.bar()
plt.title('Top 10 nation that pays their players well')
plt.ylabel('Wage')
"""
#### Look like Dominican Republic pays significantly well as compareed to other nations
"""
# Histogram dipicting the distribution of age among players
x = data.Age
sns.set(style ="dark", palette="colorblind", color_codes=True)
ax = sns.distplot(x,bins = 58,color = 'g',kde = False)
ax.set_xlabel('Age')
ax.set_ylabel('Number of players')
"""
#### So most player's age ranges from 20 - 30 years
"""
# Pieplot depicting the number of right footer vs left footer
data['Preferred Foot'].value_counts().plot.pie()
# Top 10 right footer players
right_footer = data[data['Preferred Foot'] == 'Right']
best_right_footer = right_footer[['Name','Overall']].sort_values(by = 'Overall',ascending = False)
best_right_footer[:11]
# Top 10 left footer players
left_footer = data[data['Preferred Foot'] == 'Left']
best_left_footer = left_footer[['Name','Overall']].sort_values(by = 'Overall',ascending = False)
best_left_footer[:11]
# Box plot to find whether left footer have better 'Overall' or right footer
sns.boxplot(x = data['Preferred Foot'], y = data['Overall'], data = data)
"""
#### From the above boxplot we can see that it does not matter much which is your preferred foot
"""
# Boxplot dipicting whose got better 'Shortpower', left or right?
sns.boxplot(x = data['Preferred Foot'], y = data['ShotPower'], data = data)
# Boxplot dipicting the crossing ability of left and right footer
sns.boxplot(x = data['Preferred Foot'], y = data['Crossing'], data = data)
"""
#### We can see that left footers are slightly better when it comes to crossing capability
"""
data.columns
"""
### Scatter Plots
"""
# Scatterplot dipicting the linear relationship between 'Acceleration' and 'SprintSpeed'
sns.scatterplot(x = data['Acceleration'], y = data['SprintSpeed'], data = data)
# Scatterplot dipicting the linear relationship between 'Agility' and 'SprintSpeed'
sns.scatterplot(x = data['Agility'], y = data['SprintSpeed'], data = data)
# Scatterplot dipicting the relationship between 'Agression' and 'StandingTackle'
sns.scatterplot(x = data['Aggression'], y = data['StandingTackle'], data = data, hue = data['Stamina'])
sns.scatterplot(x = data['Curve'], y = data['Crossing'], data = data, hue = data['Preferred Foot'])
"""
#### The ball crossed by a left footer would curve slightly more than a right footer`
"""
# Some body type are incorrect
data['Body Type'].value_counts()
# Changing them with normal bodytype
data['Body Type'].replace({'Messi':'Normal','Neymar':'Normal','Akinfenwa':'Normal','Shaqiri':'Normal','C. Ronaldo':
                          'Normal','PLAYER_BODY_TYPE_25':'Normal'},inplace = True)
data['Body Type'].value_counts().plot.pie()
# Boxplot for Stamina and Acceleration
sns.scatterplot(x = data['Stamina'], y = data['Acceleration'], data = data, hue = data['Body Type'])
"""
#### Majority of players with leaner body have better acceleration but less stamina
"""
sns.scatterplot(x = data['FKAccuracy'], y = data['Curve'], data = data, hue = data['Preferred Foot'])
"""
#### The more you can curve the ball better is your FreeKick Accuracy
"""
data.columns
messi = pd.DataFrame(dict(
    att=[97,94,96,86,72],
    theta=['Dribbling','FKAccuracy','BallControl',
        'SprintSpeed','Stamina']))

ronaldo = pd.DataFrame(dict(
    att=[88,76,94,91,88],
    theta=['Dribbling','FKAccuracy','BallControl',
        'SprintSpeed','Stamina']))

silva = pd.DataFrame(dict(
    att=[89,77,94,64,78],
    theta=['Dribbling','FKAccuracy','BallControl',
        'SprintSpeed','Stamina']))

neymar = pd.DataFrame(dict(
    att=[96,87,95,90,81],
    theta=['Dribbling','FKAccuracy','BallControl',
        'SprintSpeed','Stamina']))

salah = pd.DataFrame(dict(
    att=[89,60,88,91,84],
    theta=['Dribbling','FKAccuracy','BallControl',
        'SprintSpeed','Stamina']))

ramos = pd.DataFrame(dict(
    att=[63,72,84,75,84],
    theta=['Dribbling','FKAccuracy','BallControl',
        'SprintSpeed','Stamina']))
"""
### Radar Charts
"""
fig = px.line_polar(data_frame=messi ,r = 'att', theta='theta',line_close=True,title = 'Lionel Messi')
fig.update_traces(fill='toself')
fig.show()
fig = px.line_polar(ronaldo, r = 'att', theta='theta',line_close=True,title = 'Critiano Ronaldo')
fig.update_traces(fill='toself')
fig.show()
fig = px.line_polar(silva, r = 'att', theta='theta',line_close=True,title = 'David Silva')
fig.update_traces(fill='toself')
fig.show()
fig = px.line_polar(neymar, r = 'att', theta='theta',line_close=True,title = 'Neymar Jr')
fig.update_traces(fill='toself')
fig.show()
fig = px.line_polar(salah, r = 'att', theta='theta',line_close=True,title = 'Mohammad Salah')
fig.update_traces(fill='toself')
fig.show()
fig = px.line_polar(ramos, r = 'att', theta='theta',line_close=True,title = 'Sergio Ramos')
fig.update_traces(fill='toself')
fig.show()
"""
#### Radar charts dipicting the skills of few best fifa players
"""