<jupyter_start><jupyter_text>Player Analysis<jupyter_code>import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import warnings
warnings.filterwarnings("ignore")

%matplotlib inline<jupyter_output><empty_output><jupyter_text>Data Cleaning and Exploration<jupyter_code>df1 = pd.read_csv("matches.csv")
df2 = pd.read_csv("deliveries.csv")

df1.rename(columns={"id" : 'match_id'}, inplace=True)

matches= pd.merge(df1, df2, on='match_id', how='outer')
matches.columns
matches = matches[['match_id', 'season','team1', 'team2', 'toss_winner','toss_decision','dl_applied','winner',
       'inning', 'batting_team', 'bowling_team', 'over', 'ball',
       'batsman','non_striker', 'bowler','wide_runs','bye_runs', 'legbye_runs','noball_runs','penalty_runs',
       'batsman_runs', 'extra_runs', 'total_runs', 'player_dismissed',
       'dismissal_kind']]

matches.shape
matches.head()<jupyter_output><empty_output><jupyter_text>Taking in consideration KXIP VS RR matches<jupyter_code>KXIP_RR= matches[np.logical_or(np.logical_and(matches['team1']=='Kings XI Punjab',matches['team2']=='Rajasthan Royals'),
                            np.logical_and(matches['team2']=='Kings XI Punjab',matches['team1']=='Rajasthan Royals'))]
KXIP_RR = KXIP_RR[KXIP_RR["dl_applied"]==0]
KXIP_RR.match_id.nunique()
KXIP_RR.season.unique()<jupyter_output><empty_output><jupyter_text>Player to have ratio better - <NAME><jupyter_code>samson = KXIP_RR[(KXIP_RR["batting_team"]=="Rajasthan Royals")&(KXIP_RR["batsman"]=="SV Samson")]

samson.iloc[:,4:].head()
samson_runs= samson[samson["wide_runs"]==0]

batsman_runs11 = samson_runs.groupby(["match_id"]).agg({"batsman_runs":"sum","ball":"count"})

batsman_runs11
samson_runs.batsman_runs.unique()
samson_boundaries = samson_runs[(samson_runs["batsman_runs"]==4)|(samson_runs["batsman_runs"]==6)]

boundary_runs11 = pd.DataFrame(samson_boundaries.groupby(["match_id"])["batsman_runs"].sum())

boundary_runs11.columns = ["boundary runs"]

boundary_runs11
samson_ratio = pd.merge(batsman_runs11,boundary_runs11, on = "match_id" , how = "outer")

samson_ratio["boundary runs"].fillna(0, inplace = True)

samson_ratio = samson_ratio[samson_ratio["ball"]>10]

samson_ratio
samson_ratio["ratio"] = (samson_ratio["boundary runs"]/samson_ratio["batsman_runs"])

samson_ratio
samson_final_ratio = sum(samson_ratio["ratio"]/len(samson_ratio["ratio"]))

print("Average ratio for Samson :",round(samson_final_ratio*100))
sns.boxplot(samson_ratio["ratio"])
sns.kdeplot(samson_ratio["ratio"])<jupyter_output><empty_output><jupyter_text>- KL Rahul<jupyter_code>rahul = KXIP_RR[(KXIP_RR["batting_team"]=="Kings XI Punjab")&(KXIP_RR["batsman"]=="KL Rahul")]

rahul.iloc[:,4:].head()
rahul_runs= rahul[rahul["wide_runs"]==0]

batsman_runs12 = rahul_runs.groupby(["match_id"]).agg({"batsman_runs":"sum","ball":"count"})

batsman_runs12
rahul_runs.batsman_runs.unique()
rahul_boundaries = rahul_runs[(rahul_runs["batsman_runs"]==4)|(rahul_runs["batsman_runs"]==6)]

boundary_runs12 = pd.DataFrame(rahul_boundaries.groupby(["match_id"])["batsman_runs"].sum())

boundary_runs12.columns = ["boundary runs"]

boundary_runs12
rahul_ratio = pd.merge(batsman_runs12,boundary_runs12, on = "match_id" , how = "outer")

rahul_ratio = rahul_ratio[rahul_ratio["ball"]>10]

rahul_ratio
rahul_ratio["ratio"] = (rahul_ratio["boundary runs"]/rahul_ratio["batsman_runs"])

rahul_ratio
rahul_final_ratio = sum(rahul_ratio["ratio"]/len(rahul_ratio["ratio"]))

print("Average ratio for Rahul :",round(rahul_final_ratio*100))
sns.kdeplot(rahul_ratio["ratio"])
sns.boxplot(rahul_ratio["ratio"])<jupyter_output><empty_output><jupyter_text>- <NAME><jupyter_code>gayle = KXIP_RR[(KXIP_RR["batting_team"]=="Kings XI Punjab")&(KXIP_RR["batsman"]=="CH Gayle")]

gayle.iloc[:,4:].head()
gayle_runs= gayle[gayle["wide_runs"]==0]

batsman_runs21 = gayle_runs.groupby(["match_id"]).agg({"batsman_runs":"sum","ball":"count"})

batsman_runs21
gayle_runs.batsman_runs.unique()
gayle_boundaries = gayle_runs[(gayle_runs["batsman_runs"]==4)|(gayle_runs["batsman_runs"]==6)]

boundary_runs21 = pd.DataFrame(gayle_boundaries.groupby(["match_id"])["batsman_runs"].sum())

boundary_runs21.columns = ["boundary runs"]

boundary_runs21
gayle_ratio = pd.merge(batsman_runs21,boundary_runs21, on = "match_id" , how = "outer")

gayle_ratio = gayle_ratio[gayle_ratio["ball"]>10]

gayle_ratio
gayle_ratio["ratio"] = (gayle_ratio["boundary runs"]/gayle_ratio["batsman_runs"])

gayle_ratio
gayle_final_ratio = sum(gayle_ratio["ratio"]/len(gayle_ratio["ratio"]))

print("Average ratio for Gayle :",round(gayle_final_ratio*100))
sns.kdeplot(gayle_ratio["ratio"])
sns.boxplot(gayle_ratio["ratio"])<jupyter_output><empty_output><jupyter_text>- <NAME><jupyter_code>smith = KXIP_RR[(KXIP_RR["batting_team"]=="Rajasthan Royals")&(KXIP_RR["batsman"]=="SPD Smith")]

smith.iloc[:,4:].head()
smith_runs= smith[smith["wide_runs"]==0]

batsman_runs22 = smith_runs.groupby(["match_id"]).agg({"batsman_runs":"sum","ball":"count"})

batsman_runs22
smith_runs.batsman_runs.unique()
smith_boundaries = smith_runs[(smith_runs["batsman_runs"]==4)|(smith_runs["batsman_runs"]==6)]

boundary_runs22 = pd.DataFrame(smith_boundaries.groupby(["match_id"])["batsman_runs"].sum())

boundary_runs22.columns = ["boundary runs"]

boundary_runs22
smith_ratio = pd.merge(batsman_runs22,boundary_runs22, on = "match_id" , how = "outer")

smith_ratio = smith_ratio[smith_ratio["ball"]>10]

smith_ratio
smith_ratio["ratio"] = (smith_ratio["boundary runs"]/smith_ratio["batsman_runs"])

smith_ratio
smith_final_ratio = sum(smith_ratio["ratio"]/len(smith_ratio["ratio"]))

print("Average ratio for Smith :",round(smith_final_ratio*100))
sns.kdeplot(smith_ratio["ratio"])
sns.boxplot(smith_ratio["ratio"])<jupyter_output><empty_output><jupyter_text>From all the analysis we can predict <NAME> to have better ratio in this match  OPP for players<jupyter_code>def opp_batsman(player_name,opposition):
    
    player = matches[(matches["bowling_team"]==opposition)&(matches["batsman"]==player_name)]

    player_runs= player[player["wide_runs"]==0]

    batsman_runs = player_runs.groupby(["match_id"]).agg({"batsman_runs":"sum","ball":"count"})
    
    
    player_boundaries = player_runs[(player_runs["batsman_runs"]==4)|(player_runs["batsman_runs"]==6)]

    boundary_runs = pd.DataFrame(player_boundaries.groupby(["match_id"])["batsman_runs"].sum())

    boundary_runs.columns = ["boundary runs"]
    
    
    player_running = player_runs[(player_runs["batsman_runs"]==1)|(player_runs["batsman_runs"]==2)|(player_runs["batsman_runs"]==3)]

    batsman_running = pd.DataFrame(player_running.groupby(["match_id"])["batsman_runs"].sum())

    batsman_running.columns = ["running runs"]
    
    
    final = pd.merge(batsman_runs,boundary_runs, on = "match_id" , how = "outer")

    final = pd.merge(final,batsman_running,on="match_id",how = "outer")

    final["boundary runs"].fillna(0, inplace = True)

    final["running runs"].fillna(0, inplace = True)
    
    
    opp = ((final["batsman_runs"]/final["ball"]) + final["boundary runs"] + final["running runs"]) / final["ball"]
    
    opp_player = sum(opp)/len(opp)
#   print("Avg OPP for Player match_wise :", round(opp_player,2))
    return opp_player
def opp_bowler(player_name,opposition):
    
    player = matches[(matches["batting_team"] == opposition)&(matches["bowler"]==player_name)]
    
    player = player[player["wide_runs"]==0]
    
    player_bound = player[(player["batsman_runs"]==4)|(player["batsman_runs"]==6)]
    
    bound_run = pd.DataFrame(player_bound.groupby(["match_id"])["batsman_runs"].sum())
    
    bound_run.columns = ["boundary runs"]
    
    
    bound_count = pd.DataFrame(player_bound.groupby(["match_id"])["batsman_runs"].count())

    bound_count.columns = ["boundary count"]
    
    
    total_balls = pd.DataFrame(player.groupby(["match_id"])["ball"].count())
    
    
    final = pd.merge(bound_run,bound_count, on = "match_id" , how = "outer")

    final = pd.merge(final,total_balls,on="match_id",how = "outer")
 
    final["boundary runs"].fillna(0, inplace = True)

    final["boundary count"].fillna(0, inplace = True)
    
    
    opp = (final["boundary runs"]/final["boundary count"]) / final["ball"]
    
    opp.fillna(0, inplace = True)

    opp_player = sum(opp)/len(opp)
    
#    print("Avg OPP for Player match_wise :", round(opp_player,2))
    return opp_player<jupyter_output><empty_output><jupyter_text>- Batsman<jupyter_code>gayle1 = round(opp_batsman("CH Gayle","Rajasthan Royals"),2)
tewatia1 = round(opp_batsman("R Tewatia","Kings XI Punjab"),2)
rahul1 = round(opp_batsman("KL Rahul","Rajasthan Royals"),2)
stokes1 = round(opp_batsman("BA Stokes","Kings XI Punjab"),2)
mandeep1 = round(opp_batsman("<NAME>","Rajasthan Royals"),2) 
pooran1 = round(opp_batsman("<NAME>","Rajasthan Royals"),2)
maxwell1 = round(opp_batsman("<NAME>","Rajasthan Royals"),2)
uthappa1 = round(opp_batsman("RV Uthappa","Kings XI Punjab"),2)
samson1 = round(opp_batsman("<NAME>","Kings XI Punjab"),2)
buttler1 = round(opp_batsman("<NAME>","Kings XI Punjab"),2)
batsman = [gayle1,tewatia1,rahul1,stokes1,mandeep1,pooran1,maxwell1,uthappa1,samson1,buttler1]

OPP_batsman = pd.DataFrame(batsman)

OPP_batsman.columns = ["OPP"]

OPP_batsman<jupyter_output><empty_output><jupyter_text>- Bowler<jupyter_code>archer2 = round(opp_bowler("<NAME>","Kings XI Punjab"),2)
tewatia2 = round(opp_bowler("<NAME>","Kings XI Punjab"),2)
stokes2 = round(opp_bowler("<NAME>","Kings XI Punjab"),2)
shami2 = round(opp_bowler("<NAME>","Rajasthan Royals"),2)
maxwell2 = round(opp_bowler("<NAME>","Rajasthan Royals"),2)
ashwin2 = round(opp_bowler("<NAME>","Rajasthan Royals"),2)
gopal2 = round(opp_bowler("S Gopal","Kings XI Punjab"),2)
ankit2 = round(opp_bowler("AS Rajpoot","Kings XI Punjab"),2)
bowler = [archer2,tewatia2,stokes2,shami2,maxwell2,ashwin2,gopal2,ankit2]

OPP_bowler = pd.DataFrame(bowler)

OPP_bowler.columns = ["OPP"]

OPP_bowler<jupyter_output><empty_output><jupyter_text>FINAL OPP - GAYLE<jupyter_code>final_gayle = (gayle1 - min(OPP_batsman["OPP"])) / (max(OPP_batsman["OPP"]) - min(OPP_batsman["OPP"]))
print("OPP FOR GAYLE:",round(final_gayle,2))<jupyter_output>OPP FOR GAYLE: 0.22<jupyter_text>- Tewatia<jupyter_code>final_tewatia1 = (tewatia1 - min(OPP_batsman["OPP"])) / (max(OPP_batsman["OPP"]) - min(OPP_batsman["OPP"]))
final_tewatia2 = (tewatia2 - min(OPP_bowler["OPP"])) / (max(OPP_bowler["OPP"]) - min(OPP_bowler["OPP"]))
final = final_tewatia1 + final_tewatia2

print("OPP FOR Tewatia:",round(final,2))<jupyter_output>OPP FOR Tewatia: 0.23<jupyter_text>- <NAME><jupyter_code>final_rahul = (rahul1 - min(OPP_batsman["OPP"])) / (max(OPP_batsman["OPP"]) - min(OPP_batsman["OPP"]))
print("OPP FOR Rahul:",round(final_rahul,2))<jupyter_output>OPP FOR Rahul: 0.08<jupyter_text>- Stokes<jupyter_code>final_stokes1 = (stokes1 - min(OPP_batsman["OPP"])) / (max(OPP_batsman["OPP"]) - min(OPP_batsman["OPP"]))
final_stokes2 = (stokes2 - min(OPP_bowler["OPP"])) / (max(OPP_bowler["OPP"]) - min(OPP_bowler["OPP"]))
final = final_stokes1 + final_stokes2

print("OPP FOR Tewatia:",round(final,2))<jupyter_output>OPP FOR Tewatia: 1.08<jupyter_text>- Mandeep<jupyter_code>final_mandeep = (mandeep1 - min(OPP_batsman["OPP"])) / (max(OPP_batsman["OPP"]) - min(OPP_batsman["OPP"]))
print("OPP FOR Mandeep:",round(final_mandeep,2))<jupyter_output>OPP FOR Mandeep: 0.17<jupyter_text>- Pooran<jupyter_code>final_pooran = (pooran1 - min(OPP_batsman["OPP"])) / (max(OPP_batsman["OPP"]) - min(OPP_batsman["OPP"]))
print("OPP FOR Pooran:",round(final_pooran,2))<jupyter_output>OPP FOR Pooran: 0.0<jupyter_text>- Maxwell<jupyter_code>final_maxwell1 = (maxwell1 - min(OPP_batsman["OPP"])) / (max(OPP_batsman["OPP"]) - min(OPP_batsman["OPP"]))
final_maxwell2 = (maxwell2 - min(OPP_bowler["OPP"])) / (max(OPP_bowler["OPP"]) - min(OPP_bowler["OPP"]))
final = final_maxwell1 + final_maxwell2

print("OPP FOR Maxwell:",round(final,2))<jupyter_output>OPP FOR Maxwell: 1.24<jupyter_text>- Uthapa<jupyter_code>final_uthapa = (uthappa1 - min(OPP_batsman["OPP"])) / (max(OPP_batsman["OPP"]) - min(OPP_batsman["OPP"]))
print("OPP FOR Uthapa:",round(final_uthapa,2))<jupyter_output>OPP FOR Uthapa: 0.28<jupyter_text>- Samson<jupyter_code>final_samson = (samson1 - min(OPP_batsman["OPP"])) / (max(OPP_batsman["OPP"]) - min(OPP_batsman["OPP"]))
print("OPP FOR Samson:",round(final_samson,2))<jupyter_output>OPP FOR Samson: 0.25<jupyter_text>- <NAME><jupyter_code>final_buttler = (buttler1 - min(OPP_batsman["OPP"])) / (max(OPP_batsman["OPP"]) - min(OPP_batsman["OPP"]))
print("OPP FOR Buttler:",round(final_buttler,2))<jupyter_output>OPP FOR Buttler: 0.43<jupyter_text>- Archer<jupyter_code>final_archer = (archer2 - min(OPP_batsman["OPP"])) / (max(OPP_batsman["OPP"]) - min(OPP_batsman["OPP"]))
print("OPP FOR Archer:",round(final_archer,2))<jupyter_output>OPP FOR Archer: -0.74<jupyter_text>Dot balls in entire match<jupyter_code>dot_ball = KXIP_RR[KXIP_RR["total_runs"]==0]
dot_ball_overall = pd.DataFrame(dot_ball.groupby(["match_id"])["total_runs"].count())

dot_ball_overall.columns = ["dot balls"]

dot_ball_overall
dot_ball_overall.describe().T
sns.kdeplot(dot_ball_overall["dot balls"])
sns.boxplot(dot_ball_overall["dot balls"])
plt.figure(figsize=(10,7))
dot_ball_overall["Interval"] = pd.cut(dot_ball_overall["dot balls"],[60,70,80,90,100,110])
sns.countplot(dot_ball_overall["Interval"])
plt.title("No of dot balls in KXIP VS RR")
print("Average no of dot balls bowled in RR VS KXIP matches :{}".format(round(dot_ball_overall["dot balls"].mean())))<jupyter_output>Average no of dot balls bowled in RR VS KXIP matches :85<jupyter_text>Inning Wise - First Inning<jupyter_code>first_dot = dot_ball[dot_ball["inning"]==1]
first_dot_ball = pd.DataFrame(first_dot.groupby(["match_id"])["total_runs"].count())

first_dot_ball.columns = ["dot balls"]

first_dot_ball
first_dot_ball.describe().T
sns.kdeplot(first_dot_ball["dot balls"])
plt.figure(figsize=(10,7))
first_dot_ball["Interval"] = pd.cut(first_dot_ball["dot balls"],[30,35,40,45,50,55])
sns.countplot(first_dot_ball["Interval"])
plt.title("No of dot balls in 1st innings")
print("Average no of dot balls bowled in 1st innings :{}".format(round(first_dot_ball["dot balls"].mean())))<jupyter_output>Average no of dot balls bowled in 1st innings :42<jupyter_text>- 2nd innings<jupyter_code>second_dot = dot_ball[dot_ball["inning"]==2]
second_dot_ball = pd.DataFrame(second_dot.groupby(["match_id"])["total_runs"].count())

second_dot_ball.columns = ["dot balls"]

second_dot_ball
second_dot_ball.describe().T
sns.kdeplot(second_dot_ball["dot balls"])
plt.figure(figsize=(10,7))
second_dot_ball["Interval"] = pd.cut(second_dot_ball["dot balls"],[20,30,40,50,60])
sns.countplot(second_dot_ball["Interval"])
plt.title("No of dot balls in 2nd innings")
print("Average no of dot balls bowled in 2nd innings :{}".format(round(second_dot_ball["dot balls"].mean())))<jupyter_output>Average no of dot balls bowled in 2nd innings :43<jupyter_text>Confidence Interval<jupyter_code>mean = dot_ball_overall["dot balls"].mean()
sd = dot_ball_overall["dot balls"].std()
n = len(dot_ball_overall["dot balls"])

n
tstar = 2.064
se = sd/np.sqrt(n)
se
lcb = mean - tstar * se
ucb = mean + tstar * se
lcb = round(lcb)
ucb = round(ucb)


print("95% Confidence Interval for the dot balls than can be bowled in RR VS KXIP match :{}".format((lcb, ucb)))<jupyter_output>95% Confidence Interval for the dot balls than can be bowled in RR VS KXIP match :(79.0, 91.0)<jupyter_text>From all the above analysis we can prdict dot balls to be between 60-90  Balls Shami will take for his first wicket<jupyter_code>shami = matches[matches["bowler"]=="<NAME>"]
shami = shami[(shami["wide_runs"]==0)&(shami["noball_runs"]==0)]
shami = shami[shami["dismissal_kind"]!="run out"]
shami_dismissal = shami.groupby(["match_id"]).agg({"ball":"count","player_dismissed":"count"})

shami_dismissal.columns = ["total ball","wicket taken"]

shami_dismissal = shami_dismissal[shami_dismissal["wicket taken"]>0]

print("Shami's Performance :")
shami_dismissal
batsman = shami.batsman.unique()
ball =[]
f = []
for value in shami.groupby("match_id"):
    count = 0
    d = list(value[1]["player_dismissed"])
    f = list(value[1]["match_id"].unique())
    for i in d:
        count = count+1
        if(i in batsman):
            ball.append(count)
            break
ball
shami_dismissal["balls for 1st wicket"] = ball

shami_dismissal
shami_dismissal.describe().iloc[:,2:].T
sns.distplot(shami_dismissal["balls for 1st wicket"])
sns.boxplot(shami_dismissal["balls for 1st wicket"])
print("Average no. of balls taken by Shami for his first wicket :{}".format(round(shami_dismissal["balls for 1st wicket"].mean())))
plt.figure(figsize=(10,7))
shami_dismissal["Interval"] = pd.cut(shami_dismissal["balls for 1st wicket"],[0,6,12,18,24])
sns.countplot(shami_dismissal["Interval"])
plt.title("Balls for 1st wicket",fontsize = 15)<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.17514423643000118, 'fraction_numerical': 0.02060520428588249, 'mean_word_length': 8.088817549491706, 'pattern_counts': {'":': 12, '<': 108, '<?xml version=': 0, '>': 113, 'https://': 0, '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': '26', 'dir': 'jupyter-structured-clean-dedup', 'id': '611763', 'license': 'MIT', 'n_tokens_mistral': 7212, 'n_tokens_neox': 6881, 'n_words': 920, 'path': 'KXIP VS RR/Player Analysis KXIP VS RR.ipynb', 'repo_name': 'tacklesta/WPL', 'size': '17065'}