# This Python 3 environment comes with many helpful analytics libraries installed
# It is defined by the kaggle/python Docker image: https://github.com/kaggle/docker-python
# For example, here's several helpful packages to load

import numpy as np # linear algebra
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)

# Input data files are available in the read-only "../input/" directory
# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory

import os
for dirname, _, filenames in os.walk('/kaggle/input'):
    for filename in filenames:
        print(os.path.join(dirname, filename))

# You can write up to 20GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using "Save & Run All" 
# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session
"""
# **Indian Premier League (2008-2019) Exploratory Data Analysis**
"""
from IPython.display import Image
import os
!ls ../input/
Image("../input/ipljpg/ipl.jpg")
"""
****Importing required libraries****
"""
import pandas as pd
import matplotlib.pyplot as plt
import plotly.express as px
from plotly.subplots import make_subplots
import plotly.graph_objects as go
import seaborn as sns
%matplotlib inline
"""
**Datasets Description**
"""
"""
The dataset d_matches consists of data from the Season 2008 to 2019 that gives information regarding the location,matches played between various teams and the winners in each match and much more.The dataset d_deliveries further talks about which team will be batting and bowling, along with which player was batting or bowling in each inning.The dataset d_teams tells us the names of different teams that play in IPL.And finally the dataset d_team_hna talks about the matches held in home city and away and gives an eloborate detail of the same.
"""
"""
**Loading Datasets**
"""
d_matches=pd.read_csv('../input/ipl-dataset/matches.csv')
d_deliveries=pd.read_csv('../input/ipl-dataset/deliveries.csv')
d_teams=pd.read_csv('../input/ipl-dataset/teams.csv')
d_team_hna=pd.read_csv('../input/ipl-dataset/teamwise_home_and_away.csv')
d_matches.head()
d_deliveries.head()
d_teams
d_team_hna
"""
**Data Cleaning**
"""
"""
> Checking For Nan values in each dataset
"""
(d_matches.isna().sum()/len(d_matches))*100
d_matches.drop(labels='umpire3',axis=1,inplace=True)
d_matches[d_matches.city.isnull()]
"""
> Replacing Nan values from city column after comparison with venue column
"""
d_matches.loc[d_matches.venue=='Dubai International Cricket Stadium']
d_matches.city.fillna('Dubai',inplace=True) 
d_matches.dropna(axis=0,subset=['winner','player_of_match'],inplace=True)
d_matches.dropna(axis=0,subset=['umpire1','umpire2'],inplace=True)
(d_deliveries.isna().sum()/len(d_deliveries))*100
d_deliveries.drop(axis=1,columns=['player_dismissed','dismissal_kind','fielder'])
(d_teams.isnull().sum()/len(d_teams))*100
(d_team_hna.isnull().sum()/len(d_team_hna))*100
"""
**Data Analysis**
"""
"""
> 1. Number of matches in respective locations
"""
px.bar(d_matches.groupby(by='city')[['date']].count(),text='value',color_discrete_sequence= ['cornflowerblue'],labels={'value':'No.of days'},title='No.of matches played in each city')
"""
> 2. Wins by Respective Teams after winning the toss
"""
d_matches.toss_winner==d_matches.winner
df=d_matches[(d_matches.toss_winner==d_matches.winner)].groupby('winner')[['toss_winner']].count().sort_values('toss_winner')
px.line(df,x=df.index,y=df.toss_winner.values,color_discrete_sequence=['blue'],labels={'winner':'teams','y':'Matches won'},title='Matches won by teams after winning the toss')
"""
> 3. Wins procured by teams in their home city
"""
px.pie(d_team_hna,names='team',values='home_wins',color_discrete_sequence=px.colors.sequential.Plasma_r,title='Percentage of home wins')
"""
> 4. Comparison between home wins and away wins by each team
"""
px.line(d_team_hna.groupby('team')[['home_wins','away_wins']].sum(),color_discrete_sequence=['green','red'],labels={'value':'No. of wins'},title='Comparison of wins')
"""
> 5. Number of wins by each team in the 2019 season
"""
d=d_matches.loc[d_matches.season==2019].groupby('winner')[['winner']].count()
x=d.index
y=d.winner.values
f1=px.bar(data_frame=d,x=d.index,y=d.winner.values,color_discrete_sequence=['maroon'],labels={'index':'teams','y':'No.of wins'},title='Wins by each team in 2019')
f1.show()
"""
> 6. Comparing the distribution of wins by runs and wins by wickets
"""
d=d_matches.pivot_table(index=['winner'],values=['win_by_runs','win_by_wickets'],aggfunc=sum)
d.plot(kind='box',figsize=(30,10))
plt.title('Comaprison of wins by runs and wins by wickets')
plt.show()
"""
> 7. Comaparing the number of matches held in home city and away
"""
df=pd.pivot_table(data=d_team_hna,values=['home_matches','away_matches'],index='team',aggfunc='sum').sort_values(by=['home_matches','away_matches'])
fig = make_subplots(rows=1, cols=2)

fig.add_trace(go.Scatter(x=df.index, y=df.home_matches.values,name='Home Matches'),
    row=1, col=1)

fig.add_trace(
    go.Scatter(x=df.index, y=df.away_matches.values,name='Away Matches'),
    row=1, col=2)

fig.update_layout(height=600, width=800, title_text="Comparison of matches played in home city and away")
fig.show()
"""
# Observations
"""
"""
1.The number of matches held in Mumbai city is the highest followed by Kolkata and Delhi.The number of matches held in each city between 2008 to 2019 can be observed.

2.The number of matches won by each team after winning the toss can be found.In the dataset Chennai Super Kings has won the highest number of matches after winning the toss.

3.Mumbai Indians has had the most number of wins in their home city.Similarly this information the number of matches won by each team in their home city can be observed.

4.Also it is possible to compare the number of wins at home city and away for each team.

5.In the Season IPL-2019 Mumbai Indians procured the most number of wins in matches held followed by Chennai Super Kings.

6.We can find the distribution of wins by runs and wins by wickets throughout the Seasons 2008 to 2019.

7.Comparing the number of matches played by each team in their home city and away using subplots.
"""