<jupyter_start><jupyter_text>IPL Dataset Analysis Problem StatementWe want to know as to what happens during an IPL match which raises several questions in our mind with our limited knowledge about the game called cricket on which it is based. This analysis is done to know as which factors led one of the team to win and how does it matter. About the Dataset :The Indian Premier League (IPL) is a professional T20 cricket league in India contested during April-May of every year by teams representing Indian cities. It is the most-attended cricket league in the world and ranks sixth among all the sports leagues. It has teams with players from around the world and is very competitive and entertaining with a lot of close matches between teams.The IPL and other cricket related datasets are available at [cricsheet.org](https://cricsheet.org). Feel free to visit the website and explore the data by yourself as exploring new sources of data is one of the interesting activities a data scientist gets to do. About the dataset:Snapshot of the data you will be working on:The dataset 136522 data points and 24 features|Features|Description||-----|-----||match_code|Code pertaining to individual match||date|Date of the match played||city|City where the match was played||venue|Stadium in that city where the match was played||team1|team1||team2|team2||toss_winner|Who won the toss out of two teams||toss_decision|toss decision taken by toss winner||winner|Winner of that match between two teams||win_type|How did the team won(by wickets or runs etc.)||win_margin|difference with which the team won| |inning|inning type(1st or 2nd)||delivery|ball delivery||batting_team|current team on batting||batsman|current batsman on strike||non_striker|batsman on non-strike||bowler|Current bowler||runs|runs scored||extras|extra run scored||total|total run scored on that delivery including runs and extras||extras_type|extra run scored by wides or no ball or legby||player_out|player that got out||wicket_kind|How did the player got out||wicket_fielders|Fielder who caught out the player by catch|  Load the data<jupyter_code># Read the data using pandas module.
import pandas as pd
import numpy as np

import warnings
warnings.filterwarnings('ignore')
data = pd.read_csv('../data/ipl_data.csv', parse_dates=['date'])
data.head()<jupyter_output><empty_output><jupyter_text>There are matches being played all around the world. Find the list of unique cities where matches are being played throughout the world.<jupyter_code>print('Cities these matches were played at: \n', data['city'].unique())
data.loc[data['city'] == 'neutral_venue', 'venue'].unique()<jupyter_output><empty_output><jupyter_text>Find columns containing null values if any.<jupyter_code>data.info()
null_cols = data.isnull().sum()
print('List of columns where null values are present: \n', null_cols[null_cols > 0].index.tolist())<jupyter_output>List of columns where null values are present: 
 ['winner', 'win_type', 'win_margin', 'extras_type', 'player_out', 'wicket_kind', 'wicket_fielders']<jupyter_text>Why we have null values for winner column?<jupyter_code>data.loc[data['winner'].isnull(), 'match_code'].unique()<jupyter_output><empty_output><jupyter_text>Matches are played throughout the world in different countries but they may or may not have multiple venues(stadiums where matches are played).<jupyter_code>multi_stadium = data.groupby('city')['venue'].nunique().nlargest(5)
multi_stadium
#data[data['city'].isin(multi_stadium)].groupby('city').unique()<jupyter_output><empty_output><jupyter_text>Find the top 5 venues where the most matches are played.<jupyter_code># Top 5 venues where most ball were bowled!
data['venue'].value_counts().nlargest(5)
# Top 5 venues where most matches were played!
data.groupby('venue')['match_code'].nunique().nlargest(5)<jupyter_output><empty_output><jupyter_text>Find out how the runs were scored that is the runs count frequency table( number of singles, doubles, boundaries, sixes etc were scored).<jupyter_code>data['runs'].value_counts(sort=False)
data['runs'].value_counts(sort=False).plot.barh();<jupyter_output><empty_output><jupyter_text>Is there difference in runs frequency w.r.t. innings?<jupyter_code>data.groupby('inning')['runs'].value_counts(sort=False).unstack().T.plot.bar(rot=0);<jupyter_output><empty_output><jupyter_text>IPL seasons are held every year now let's look at our data and extract how many seasons and which year were they played?<jupyter_code>data['year'] = data['date'].dt.year
data['year']
print('Number of seasons:', data['year'].nunique())
print('Seasons were played at years: ', data['year'].sort_values().unique())<jupyter_output>Number of seasons: 9
Seasons were played at years:  [2008 2009 2010 2011 2012 2013 2014 2015 2016]<jupyter_text>Find out the total number of matches played in each season also find the total number of runs scored in each season.<jupyter_code>data.groupby('year')['match_code'].nunique().plot.barh(title='Matches played per season');
data.groupby('year')['total'].sum().plot.barh(title='Total runs scored per season');
# Average runs per match
data.groupby('match_code')['total'].sum().mean()<jupyter_output><empty_output><jupyter_text>There are teams which are high performing and low performing. Let's look at the aspect of performance of an individual team. Filter the data and aggregate the runs scored by each team. Display top 10 results which are having runs scored over 200.<jupyter_code>total_scores = data.groupby(['match_code', 'inning', 'batting_team'])['total'].sum().reset_index()
high_scores = total_scores[total_scores['total'] >= 200]
high_scores.nlargest(10, columns='total')<jupyter_output><empty_output><jupyter_text>Chasing a 200+ target is difficulty in T-20 format. What are the chances that a team scoring runs above 200 in their 1st inning is chased by the opposition in 2nd inning.<jupyter_code># Inning 1 team must score 200+ scores
high_scores_1 = high_scores.loc[high_scores['inning']==1, :]
high_scores_1.head()
# Slice 2nd inning matches similar to the match code of 200+ scored inning 1
high_scores_2 = total_scores.loc[total_scores['inning']==2, :]
high_scores_2 = high_scores_2.loc[high_scores_2['match_code'].isin(high_scores_1['match_code'].values), :]
high_scores_2.head()
high_scoring_matches = high_scores_1.merge(high_scores_2, on='match_code', suffixes=['_inn1', '_inn2']).drop(columns=['inning_inn1', 'inning_inn2'])
high_scoring_matches
high_scoring_matches['is_chased'] = high_scoring_matches['total_inn2'] > high_scoring_matches['total_inn1']
high_scoring_matches
chances = high_scoring_matches['is_chased'].value_counts(normalize=True).multiply(100).round(2)[1]
print('Chances of chasing 200+ target is', chances)<jupyter_output>Chances of chasing 200+ target is 14.63<jupyter_text>Every season has that one team which is outperforming others and is in great form. Which team has the highest win counts in their respective seasons ?<jupyter_code>match_wise_data = data.drop_duplicates(subset='match_code', keep='first').reset_index(drop=True)

match_wise_data.groupby('year').apply(
    lambda group: pd.Series(
        [group['winner'].value_counts().index[0], group['winner'].value_counts()[0]], index=['winner', 'count']
    )
)<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.1095852787695688, 'fraction_numerical': 0.017165613842351, 'mean_word_length': 7.128348214285714, 'pattern_counts': {'":': 0, '<': 50, '<?xml version=': 0, '>': 53, 'https://': 1, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '13', 'dir': 'jupyter-structured-clean-dedup', 'id': '458971', 'license': 'Apache-2.0', 'n_tokens_mistral': 2301, 'n_tokens_neox': 2158, 'n_words': 722, 'path': '18_IPL Dataset analysis using more loops and conditionals/notebook/IPL_data_analysis.ipynb', 'repo_name': 'hirenhk15/ga-code-alongs', 'size': '7282'}