!jt -t oceans16
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
import math
from collections import Counter
ipl = pd.read_csv('../input/ipl-complete-dataset-20082020/IPL Matches 2008-2020.csv', parse_dates = True, index_col = 2)

## Cleaning The Data##

ipl = ipl.drop(columns = ['id','method'])

## check for Columns with NaN Values

sns.set_style('dark')

plt.rcParams["figure.figsize"] = (28,6)

ipl.isna().sum().plot(kind = 'bar',color = '#00afb9',label = "Number of NaN's")

plt.xlabel('Columns', color = '#f07167', fontsize = 20)

plt.ylabel("Number of Missing Values", color = '#f07167', fontsize = 20)

plt.title("MISSING VALUES", color  = '#0081a7', fontsize = 20)

plt.xticks(rotation = 90, color = '#6d597a', fontsize = 20)

plt.yticks(color = '#6d597a', fontsize = 20)

plt.axhline(y = 4, label = "Four columns with Similar number of NaN Values", linestyle = '--')

plt.legend(fontsize = 20)

plt.annotate(xy =(10,16) ,xytext =(4,10) ,text ='"result_margin" column has largest number of NaN Values'\
             ,arrowprops = {'arrowstyle':'simple','color':'#00296b'}, fontsize = 20, color = "#1f2041")
plt.show()

plt.clf()

"""
# Filling up the NaN values
***
#### As we can see 'city' Column and 'result_margin' column Have most NaN values. I will fill city columns NaN values with 'Unknown Venue'. And Result Margin will be filled with value 0.
***
#### Alse note that columns = ['player_of_match','winner','result','eliminator'] have Similar amount of NaN. I have researched a bit and these tend to be No results. I will Fill these with 'No Result'. But I dont think 'eliminator' Column is that important. So I will leave it as it is.
"""
## Cleaning Data From NaN Values

ipl['city'] = ipl['city'].fillna('Unkown City')

ipl['winner'] = ipl['winner'].fillna('No Result')

ipl['result'] = ipl['result'].fillna('No Result')

ipl['player_of_match'] = ipl['player_of_match'].fillna('No Result')

ipl['result_margin'] = ipl['result_margin'].fillna(0)
##Umpires in IPL History##

## Extracting Umpire Data from the IPL Data##

umpire1 = ipl['umpire1'].to_list()

umpire2 = ipl['umpire2'].to_list()

umpire_df = pd.DataFrame()

umpire_df['Total_umpires'] = umpire1+umpire2

## Plotting the extracted data to get insights##

umpire = sns.catplot(kind = 'count',x = 'Total_umpires', data = umpire_df, color  = '#00afb9')

##Customising the PLOT##

sns.set_style('dark')

umpire.fig.set_size_inches([28,6])

plt.title("Number of Matches Umpired per Unique Umpire", fontsize = 20, color  = '#0081a7')

plt.xlabel("Umpires", color = '#fb5607', fontsize = 20)

plt.ylabel('Match Count',  color = '#fb5607', fontsize = 20)

plt.xticks(rotation = 90, color = '#6d597a', fontsize = 20)

plt.yticks(color = '#6d597a', fontsize = 20)

plt.annotate( xy = (20, 120), fontsize = 20,text = 'S Ravi Tops with 120 Matches',\
            arrowprops = {'arrowstyle':'simple', 'color':'#00296b'}, xytext = (21,115), color = "#1f2041")
plt.show()

plt.clf()
"""
# Umpiring facts that I observed from the data
***

"""
"""
#### 1) <span style = 'color:#0081a7'>S. Ravi</span> holds the distinction of Umpiring most number of matches in the IPL
#### 2) In the entire History of IPL <span style = 'color:#0081a7'>56</span> Different Umpires have Supervised IPL Matches
"""
"""
# Modes of wins in IPL
"""
pop = 0

sns.set_palette('YlGnBu')

explode1 = [ 0 if x != 'No Result' else 0.2 for x in ipl['result'].value_counts().index ]

plt.pie(ipl['result'].value_counts(),explode = explode1, autopct = '%1.1f%%')

plt.legend(labels = ipl['result'].value_counts().index , fontsize = 20, loc = 'upper right', bbox_to_anchor=(1.5,0.9))

plt.show()

plt.clf()
## Corrcting the Error OF Chinnaswamy Stadium##

ipl = ipl.replace(['M Chinnaswamy Stadium'],'M.Chinnaswamy Stadium')

## Creating a Count Plot withrespect to Venue at which mathces are held##

g = sns.catplot(x = 'venue', data = ipl, kind = 'count', color = '#00afb9')

##customising the Plot##

sns.set_style('dark')

g.fig.set_size_inches([28,6])

# g.fig.suptitle("No of Cricket Matches in Different Venues", color  = '#7209b7',y = 0.945)

plt.title("Number of Cricket Matches in Different Venues", fontsize = 20, color  = '#0081a7')

plt.ylabel('Number of Matches Per Stadium',color = '#fb5607')

plt.xlabel('Stadium', color = '#fb5607', fontsize = 20)

plt.xticks(rotation = 90, color = '#6d597a', fontsize = 20)

plt.yticks(color = '#6d597a', fontsize = 20)

plt.annotate(xy = (0,78), xytext = (10,70), fontsize = 20, arrowprops = {'arrowstyle':'simple', 'color':'#00296b'},\
            text = "M.Chinnaswamy Stadium Hosted Most IPL Matches", color = "#1f2041")

plt.show()

plt.clf()
"""
# M.Chinnaswamy Stadium
#### As we can see from the above countplot M.Chinnaswamy Stadium in Chennai Held Most IPL Matches.
"""
# Overall Teams

print(ipl['winner'].unique())
"""
# Errors in the IPL Team List
#### We have Noticed a Entry error. Both Risisng Pune Supergiants and Rising Pune Supergiant are obivously same team. But due to wrong entry we have Rising Pune Supergaints which is not the name of franchise. We should Correct This Error.
"""
"""
# Re-Branding of Delhi and HyderaBad
#### Both The Delhi DareDevils and the Delhi Capitals are the same team. The Delhi daredevils in 2018 renamed to Delhi capitals. And also Deccan Charges were acquired by a new owner and was Renamed to Sunrisers hyderabad. So for the Sake of Better Coding Lets Rename Delhi Daredevils to Delhi capitals and Deccan Chargers to Sunrisers Hyderabad in 'ipl' DataFrame. Specifically in the column 'winner'
"""
#Correcting Errors and Rebranding Team names

ipl = ipl.replace(['Delhi Daredevils'],'Delhi Capitals')

ipl = ipl.replace(['Rising Pune Supergiants'],'Rising Pune Supergiant')

ipl = ipl.replace(['Deccan Chargers'],'Sunrisers Hyderabad')

print(ipl['winner'].unique())

ipl_teams = list(ipl['winner'].unique())

ipl_cities  = list(ipl['city'].unique())
"""
# Overall
#### The Above list is the Cleaned Version of Teams that participated in Ipl History. From the list we can count 13 Unique teams that participated.
"""
## Lets See Who won the Most ##

winner = sns.catplot(kind = 'count', x = 'winner', data = ipl, color  = '#00afb9')

## Customising the Plot ##

sns.set_style('dark')

winner.fig.set_size_inches([28,6])

plt.title("Number of Matches Won by Each Franchise", fontsize = 20, color  = '#0081a7')

plt.ylabel('Wins',color = '#fb5607', fontsize = 20)

plt.xlabel('IPL Franchises', color = '#fb5607', fontsize = 20)

plt.xticks(rotation = 90, color = '#6d597a', fontsize = 20)

plt.yticks(color = '#6d597a')

plt.annotate(xy = (7,118), xytext = (8,120), fontsize = 20, arrowprops = {'arrowstyle':'simple', 'color':'#00296b'},\
            text = "Mumbai Indians Won most Matches", color = "#1f2041")
plt.show()

plt.clf()
##Plot For Cities Which Hosted Ipl##

sns.set_style('dark')

city = sns.catplot(x = 'city', data = ipl, kind ='count', color  = '#00afb9')

## customizing the Plot ##

city.fig.set_size_inches([28,6])

plt.title('Number of Matches Per City', color  = '#0081a7',fontsize = 20)

plt.ylabel('Number of Matches Per City',color = '#fb5607', fontsize = 20)

plt.xlabel('City', color = '#fb5607', fontsize = 20)

plt.xticks(rotation = 90, color = '#6d597a', fontsize = 20)

plt.yticks(color = '#6d597a', fontsize = 20)

##Adding Annotations##

plt.annotate(xy = (27,13), xytext = (24,40), fontsize = 20, arrowprops = {'arrowstyle':'simple', 'color':'#00296b'},\
            text = "Note That there are 13 Unknown Cities", color = "#1f2041")

plt.annotate(xy = (4,100), xytext = (7,65), fontsize = 20, arrowprops = {'arrowstyle':'simple', 'color':'#00296b'},\
            text = "Mumbai Hosted Most IPL Matches and \nInterestigly Its the home town of Mumbai Indians the team with most wins in IPL"\
             , color = "#1f2041")

plt.show()

plt.clf()
"""
# Observations From Above Two Plots
#### Mumabai Indians are the Team with most Number of wins(with 120 wins) in IPL and Mumbai which is there home City also hosted most number of IPL Matches .

#### This assumed correlation screams of "HOME ADVANTAGE". Lets see if such a term really holds value in the face of real data.
"""
## Filtering ipl Data Frame##

""" Let's cretate a Data Frame from ipl Data Frame with condition that Mumbai indians won the match"""

ipl_mi_won = ipl[ipl['winner'] == 'Mumbai Indians']

sns.set_palette('YlGnBu')

fig, ax = plt.subplots()

explode = [0.1 if city == 'Mumbai' else 0 for city in ipl_mi_won['city'].value_counts().index ]

ax.pie(ipl_mi_won['city'].value_counts(), explode = explode, autopct='%1.1f%%', shadow = True)

## customization ##

ax.legend(loc = 'upper right', bbox_to_anchor=(1.2,0.9), labels = ipl_mi_won['city'].value_counts().index )

ax.annotate(xy = (0.4,0.9), xytext = (1.5,1.5), fontsize = 20, arrowprops = {'arrowstyle':'simple', 'color':'#00296b'},color = "#1f2041", \
            text ="Proving our Hypothesis True Mumbai Indians won 53 matches in Mumbai that is 44.2% of thier total 120 wins")

fig.set_size_inches([32,9])

plt.plot()
# lets remove rows with result == 'No Result' ##

ipl_without_no_result = ipl[ipl['winner'] != 'No Result']

##Forming a Facet Grid##

g = sns.catplot(kind = 'count', x= 'city', data = ipl_without_no_result, col ='winner', col_wrap = 3, color  = '#00afb9')

g.set_xticklabels(rotation = 90,color = '#6d597a' )

g.set_yticklabels(color = '#6d597a')

g.set_xlabels('Cities' ,color = '#fb5607')

g.set_ylabels('Wins in the city',color = '#fb5607')

g.set_titles( color  = '#0081a7')

g.add_legend()

plt.show()

plt.clf()
"""
### From the above Facet Grid it's pretty clear that Home Matches constitute a major chunk of Teams total match wins.
### Lets further explore to seee if "Home Advantage" is Fictional or Real 
"""
### Extracting data to Visualise Info ###
team_and_thier_best_city = []

percentage_of_wins = []

for team in ipl_without_no_result['winner'].unique():
    data = ipl_without_no_result[ipl_without_no_result['winner'] == team]['city'].value_counts(normalize =True)
    team_and_thier_best_city.append(f'{team} at {list(data.index)[0]}')
    percentage_of_wins.append(data.max()*100)
    

### Forming A bar plot using the Lists we created ###

sns.barplot(x = team_and_thier_best_city, y = percentage_of_wins, color  = '#00afb9')

### customization ###

plt.xticks(rotation = 90, fontsize = 20,color = '#6d597a')

plt.yticks( [0,10,20,30,40],['0%','10%','20%','30%','40%'],fontsize = 20,color = '#6d597a')

plt.ylabel("Percentage of wins", fontsize = 20, color = '#fb5607')

plt.xlabel("Teams at cities where they won most", fontsize = 20, color = '#fb5607')

plt.title("Pecentage of wins at  Home ", color  = '#0081a7', fontsize = 20)

plt.axhline(np.mean(percentage_of_wins), label = 'Mean', linestyle = '--', color = '#0077b6')

plt.legend(fontsize = 20)

plt.show()
"""
### Team have an average 35% of thier total wins at Home. From this we can conclude that "Home Advantage" is not A myth

***

"""
"""
# Importance of TOSS
### While we proved Home Advantage is not fictious. There is one more Aspect of a cricket match which cricket community deem quite important and that is winning a toss. People feel that winning a toss can give a team massive advantage. Lets explore if it's True.
"""
print(len(ipl_without_no_result[ipl_without_no_result['toss_winner'] == ipl_without_no_result['winner']].index))
print(len(ipl_without_no_result[ipl_without_no_result['toss_winner'] != ipl_without_no_result['winner']].index))
"""
### As we can see '418' times did teams win the toss and won the match and '394' times teams won the toss and still lost the match. with just 24 matches of difference we can say that winnig a TOSS doesnt help you in winning matches
"""
"""
***
"""
"""
# Conclusions and Some Finds
* Of 56 umpires to have umpired in IPL ***S.Ravi*** Umpired Most number of IPL matches with 120 matches
* ***M.Chinnaswamy*** Stadium in Banglore hosted most number of IPL matches. A whooping 80 matches were held at this Venue
* ***Mumbai*** as a city hosted most number of IPL matches and The Mumbai's home team ***Mumbai Indians*** won most number of IPL matches
* When we dug further we were able to see that Home Advantage is Real and playing at home does help teams
* But winning a toss doesnt seems to have a deterministic effect on a match's outcome. 
"""
"""
# With this I wave you a Good Bye!! Take care and wear masks.
"""