<jupyter_start><jupyter_text>**TASK 4 - Exploratory Data Analysis - Sports*** Perform ‘Exploratory Data Analysis’ on dataset ‘Indian Premier League’* As a sports analysts, find out the most successful teams, players and factors contributing win or loss of a team.* Suggest teams or players a company should endorse for its products. Author - <NAME>--- ***Importing all necessary libraries.***<jupyter_code>import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
%matplotlib inline
import warnings
warnings.filterwarnings('ignore')<jupyter_output><empty_output><jupyter_text>***Reading and displaying the data from the Indian Premier League dataset.***<jupyter_code>match = pd.read_csv("matches.csv")
match.tail(1)
match.id.is_unique
delivery = pd.read_csv("deliveries.csv")
delivery.tail(1)
match.shape
delivery.shape
match[match.city.isnull()][['city','venue']]
match.city = match.city.fillna('Dubai')
match[match.player_of_match.isnull()][['player_of_match','result']]
match[(match.umpire1.isnull()) | (match.umpire2.isnull())]
match.winner.value_counts()
season=match[['id','season','winner']]
merge=delivery.merge(season,how='inner',left_on='match_id',right_on='id')
merge.describe().T
match.columns.values
match = match.drop(columns=["umpire3"],axis=1)
match.tail(1)
print("Basic Info Of Matches : \n")
print('Number Of Matches Played :',match.shape[0])
print("Number Of Seasons Played : ",match['season'].value_counts().nunique())
print("Top 10 Prominent Players of IPL : \n", match['player_of_match'].value_counts()[:10])
print("Most Winning Team and Number Of Matches: \n",match['winner'].value_counts())
print("Most Winning Team: \n",match['winner'].value_counts().idxmax())
print("Player Of The Match & Number Of Matches : \n",match['player_of_match'].value_counts())
print("Player Of The Match For Max . Matches : \n",match['player_of_match'].value_counts().idxmax())
print("Seasons Played at Different Venues :\n",match.groupby('city')['season'].nunique())
print("Winners at Different Venues :\n",match.groupby('city')['winner'].nunique())
print("Winners in Cities \n",match.groupby('city')['winner'].value_counts())
city_venue = match.groupby(['city','venue']).count()['season']
city_venue_df = pd.DataFrame(city_venue)
city_venue_df
plt.figure(figsize = (20,10))
sns.countplot('season',data=match)
plt.title("Number of Matches played in each IPL season",fontsize=15)
plt.xlabel("season",fontsize=15)
plt.ylabel('Matches',fontsize=15)
plt.show()
plt.figure(figsize = (20,10))
sns.countplot(x='winner',data=match, palette='husl')
plt.title("Numbers of matches won by team ",fontsize=15)
plt.xticks(rotation=50)
plt.xlabel("Teams",fontsize=15)
plt.ylabel("No of wins",fontsize=15)
plt.show()
merge.groupby(['batting_team','season'])['batsman_runs'].sum().unstack().plot(kind = 'bar',stacked = True ,
                                                                                figsize = (20,10))
plt.title("Runs by Years for Each Team",fontsize= 15, fontweight = 'bold')
plt.xlabel("Teams", size = 12)
plt.ylabel("Total Runs Scored", size = 12)
plt.xticks(size = 25)
plt.yticks(size = 25)
match['win_by']=np.where(match['win_by_runs']>0,'Bat first','Bowl first')
Win=match.win_by.value_counts()
labels=np.array(Win.index)
sizes = Win.values
colors = ['lime','orange']
plt.figure(figsize = (10,8))
plt.pie(sizes, labels=labels, colors=colors, autopct='%1.1f%%', shadow=True,startangle=90)
plt.title('Match Result',fontsize=15)
plt.show()
plt.figure(figsize = (20,10))
sns.countplot('season',hue='win_by',data=match,palette='hsv')
plt.title("Numbers of matches won by batting and bowling first ",fontsize=15)
plt.xlabel("Season",fontsize=15)
plt.ylabel("Count",fontsize=15)
plt.show()
Toss=match.toss_decision.value_counts()
labels=np.array(Toss.index)
sizes = Toss.values
colors = ['yellow', 'green']
plt.figure(figsize = (10,8))
plt.pie(sizes, labels=labels, colors=colors,
        autopct='%1.1f%%', shadow=True,startangle=90)
plt.title('Toss result',fontsize=15)
plt.show()
match['toss_win_game_win'] = np.where((match.toss_winner == match.winner),'Yes','No')
match.head(1)
plt.figure(figsize=(10,5))
sns.countplot('toss_win_game_win', data=match, palette='husl')
plt.title("Does Winning toss help in winning match?",fontsize=15,fontweight="bold")
plt.ylabel("Frequency", size = 15)
plt.xlabel("Winning Matches Based on Winning Woss", size =15)
plt.xticks(size = 15)
plt.yticks(size = 15)
plt.figure(figsize = (20,10))
sns.countplot('season',hue='toss_decision',data=match,palette='Greens')
plt.title("Numbers of matches won by Toss result ",fontsize=15)
plt.xlabel("Season",fontsize=15)
plt.ylabel("Count",fontsize=15)
plt.show()
match_final=match.drop_duplicates(subset=['season'], keep='last')
match_final[['season','winner']].reset_index(drop=True).sort_values('season')
plt.figure(figsize = (20,10))
top_players = match.player_of_match.value_counts()[:10]
fig, ax = plt.subplots()
ax.set_ylim([0,20])
ax.set_title("Top Man of the Match")
top_players.plot.bar()
sns.barplot(x = top_players.index, y = top_players, orient='v', palette="hsv");
plt.show()
match_final.groupby(['city','winner']).size()
match_final["winner"].value_counts()
match_final[['toss_winner','toss_decision','winner']].reset_index(drop=True)
match_final[['winner','player_of_match']].reset_index(drop=True)
fours=merge[merge['batsman_runs']==4]
fours.groupby('batting_team')['batsman_runs'].agg([('runs by fours','sum'),('fours','count')])
player_four=fours.groupby('batsman')['batsman_runs'].agg([('four','count')]).reset_index().sort_values('four',ascending=0)
ax=player_four.iloc[:10,:].plot('batsman','four',kind='bar',color='darkgreen')
plt.title("Numbers of Fours scored by Batsman",fontsize=15)
plt.xticks(rotation=50)
plt.xlabel("Batsman Name",fontsize=15)
plt.ylabel("Number of Fours",fontsize=15)
plt.show()
ax=fours.groupby('season')['batsman_runs'].agg([('four','count')]).reset_index().plot('season','four',kind='bar',color = 'limegreen')
plt.title("Numbers of Fours Hit in Each Season ",fontsize=15)
plt.xticks(rotation=50)
plt.xlabel("Season",fontsize=15)
plt.ylabel("Number of Fours",fontsize=15)
plt.show()
sixes=merge[merge['batsman_runs']==6]
sixes.groupby('batting_team')['batsman_runs'].agg([('runs by six','sum'),('sixes','count')])
six_player=sixes.groupby('batsman')['batsman_runs'].agg([('six','count')]).reset_index().sort_values('six',ascending=0)
ax=six_player.iloc[:10,:].plot('batsman','six',kind='bar',color='green')
plt.title("Numbers of Sixes Hit by Batsman",fontsize=15)
plt.xticks(rotation=50)
plt.xlabel("Batsman Name",fontsize=15)
plt.ylabel("Number of Sixes",fontsize=15)
plt.show()
batsman_score=delivery.groupby('batsman')['batsman_runs'].agg(['sum']).reset_index().sort_values('sum',
                            ascending=False).reset_index(drop=True)
batsman_score=batsman_score.rename(columns={'sum':'batsman_runs'})
print("Top 10 Run Scorer in IPL")
batsman_score.iloc[:10,:]
matches_played=delivery[["match_id","player_dismissed"]]
matches_played=matches_played.groupby("player_dismissed")["match_id"].count().reset_index().sort_values(by="match_id",ascending=False).reset_index(drop=True)
matches_played.columns=["batsman","No_of Matches"]
matches_played.T
plt.figure(figsize=(20,8))
ax=sns.countplot(delivery.dismissal_kind)
plt.title("Wickets in IPL",fontsize=15)
plt.xlabel("Wicket Type",fontsize=15)
plt.ylabel("count",fontsize=15)
plt.xticks(rotation=90)
plt.show()
wicket_data=delivery.dropna(subset=['dismissal_kind'])
wicket_data=wicket_data[~wicket_data['dismissal_kind'].isin(['run out','retired hurt','obstructing the field'])]
wicket_data.groupby('bowler')['dismissal_kind'].agg(['count']).reset_index().sort_values('count',
        ascending=False).reset_index(drop=True).iloc[:10,:]
wides = pd.DataFrame(merge.groupby('bowler')['wide_runs'].sum())
noballs = pd.DataFrame(merge.groupby('bowler')['noball_runs'].sum())
season = pd.DataFrame(merge.groupby('bowler')['season'].nunique())
extras_bowlers = pd.DataFrame({'wides':wides['wide_runs'],'no_balls':noballs['noball_runs']})
extras_bowlers.reset_index(inplace = True)

extras_bowlers['total_extras'] = extras_bowlers['wides'] + extras_bowlers['no_balls']
most_extras = extras_bowlers.sort_values(by='total_extras', ascending = False).head(15)
extras_bowlers.style.apply(lambda x: ['background: white' if x.name in [6] else '' for i in x], axis=1)
plt.figure(figsize = (20,8))
sns.barplot(x ='bowler', y='wides', data= most_extras)
sns.barplot(x ='bowler', y='no_balls', data= most_extras)
plt.title("Extras given by Bowlers",fontsize= 15, fontweight = 'bold')
plt.xlabel("Player", size = 15)
plt.ylabel("Wides and No balls", size = 15)
plt.xticks(size = 10)
plt.yticks(size = 14)<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.19005714285714287, 'fraction_numerical': 0.02022857142857143, 'mean_word_length': 8.319488817891374, 'pattern_counts': {'":': 0, '<': 10, '<?xml version=': 0, '>': 11, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 3, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '2', 'dir': 'jupyter-structured-clean-dedup', 'id': '67806', 'license': 'MIT', 'n_tokens_mistral': 3371, 'n_tokens_neox': 3159, 'n_words': 506, 'path': 'Task5-EDA(Sports)/ExploratoryDataAnalysisSports.ipynb', 'repo_name': 'LiquidisedFish/TSF-GRIP-Tasks', 'size': '8759'}