{"cells":[{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true,"_kg_hide-input":true,"_kg_hide-output":true},"cell_type":"code","source":"'''Import basic modules.'''\nimport pandas as pd\nimport numpy as np\n\n'''visualization Tools'''\nimport altair as alt\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nsns.set_style(\"whitegrid\")\n%matplotlib inline\n\n'''Bokeh (interactive visualization)'''\nfrom bokeh.plotting import figure, show,output_notebook, ColumnDataSource\nfrom bokeh.layouts import row\noutput_notebook() \n\n'''Plotly visualization .'''\nimport plotly.offline as py\nfrom plotly.offline import iplot, init_notebook_mode\nimport plotly.graph_objs as go\npy.init_notebook_mode(connected = True)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# NCAA® March Madness: Exploratory Analysis\n![](https://adeshpande3.github.io/assets/Cover8th.png)"},{"metadata":{},"cell_type":"markdown","source":"# About March Madness\n\nThe NCAA college basketball tournament is a single-elimination tournament that features 68 teams vying to survive three weekends of games to be crowned the national champions. The field used to be 64 teams, but the NCAA has recently added four more teams that play \"play in\" games to earn a spot in the final field of 64.\n\nOnly 16 teams (the \"Sweet Sixteen\") make it past the first weekend. The second weekend narrows the field first to the \"Elite Eight\" and then the \"Final Four. The final weekend focuses on the four semifinalists. The two semifinal victors move on to play in the national championship game.\n\nOhio State University coach Harold Olsen is usually credited with developing the idea for the tournament in 1939 with the help of the National Association of Basketball Coaches.\n\nThe 68 teams in the tournament include 32 teams that receive automatic bids for winning their respective conferences. The remaining 36 teams are given at-large bids by the NCAA selection committee based upon their performance during the season.\n\nOnce the field is set, the teams are divided into four regions (usually spread geographically through the eastern, western, midwestern, and southern U.S.) and placed into a bracket that lays out the path a team must take to reach the finals. Each team is seeded or ranked within its region, from 1 to 16.\n\nHigher-seeded teams generally play lower-seeded teams in the beginning. For example, in the first round, each team seeded #1 plays the team seeded #16. This trend continues until upsets begin to occur, at which time brackets can become hard to predict as unexpectedly-good teams (often called \"Cinderella\" teams) make a run in the tournament.\n[**Source**](https://www.wonderopolis.org/wonder/what-is-march-madness).\n**For better understanding about March Madness visit @parulpandey** [Kernel](https://www.kaggle.com/parulpandey/decoding-march-madness/#data)\n![](https://media0.giphy.com/media/Jve9N0AwwXiiQ/source.gif)"},{"metadata":{},"cell_type":"markdown","source":"# Introduction\nAlthough I am not a huge college basketball fan, I find this particular data set fascinating in its richness. Let’s dig in and see what we can learn about the history of March Madness.The below analysis will be conducted on both the regular season and tournament statistics. It will begin by taking a high level view at the NCAA championships - who has won them and how. Hopefully along the way, I’ll discover something useful to use in your models."},{"metadata":{},"cell_type":"markdown","source":"# Data Section 1 - The Basics\nThis section provides exploratory data analysis (EDA) of: \n * Team ID's and Team Names\n * Historical tournament seeds\n * Final scores of historical regular season, conference tournament, and NCAA® tournament games\n * Season-level details including dates and region names\n \nData Section 1 - The Basics ==> [File descriptions](https://www.kaggle.com/c/march-madness-analytics-2020/data)"},{"metadata":{"trusted":true},"cell_type":"code","source":"mteams = pd.read_csv('../input/march-madness-analytics-2020/2020DataFiles/2020-Mens-Data/MDataFiles_Stage1/MTeams.csv')\nmseasons = pd.read_csv('../input/march-madness-analytics-2020/2020DataFiles/2020-Mens-Data/MDataFiles_Stage1/MSeasons.csv')\nmtourney_seed = pd.read_csv('../input/march-madness-analytics-2020/2020DataFiles/2020-Mens-Data/MDataFiles_Stage1/MNCAATourneySeeds.csv')\nmseason_results = pd.read_csv('../input/march-madness-analytics-2020/2020DataFiles/2020-Mens-Data/MDataFiles_Stage1/MRegularSeasonCompactResults.csv')\nmtourney_results = pd.read_csv('../input/march-madness-analytics-2020/2020DataFiles/2020-Mens-Data/MDataFiles_Stage1/MNCAATourneyCompactResults.csv')\nconference = pd.read_csv('../input/march-madness-analytics-2020/2020DataFiles/2020-Mens-Data/MDataFiles_Stage1/Conferences.csv')\nteam_conference = pd.read_csv('../input/march-madness-analytics-2020/2020DataFiles/2020-Mens-Data/MDataFiles_Stage1/MTeamConferences.csv')","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Which Team Wins And Lost The Most Tournaments? "},{"metadata":{"_kg_hide-input":true,"trusted":true},"cell_type":"code","source":"# data preparation\nwteam = mtourney_results.rename(columns={'WTeamID':'TeamID'}) # rename the WteamID as TeamID for merge with mteams dataframe\nwin_team =  wteam.merge(mteams, on='TeamID')                  # merge with mteams dataframe\n#win_team = win_team.rename(columns={'TeamID':'WTeamID_X'})\ntemp = win_team['TeamName'].value_counts().head(15).reset_index()\n\n# Create ColumnDataSource from data frame\nsource = ColumnDataSource(temp)\nwin_team_list = source.data['index'].tolist()\n\n# Add Plot\np = figure(\n    y_range = win_team_list,\n    plot_width=600,\n    plot_height=320,\n    title=\"Most Tournament Wins since 1985\",\n    y_axis_label='Winners',\n    tools=\"\"\n    \n)\np.title.text_font = 'helvetica'\np.title.text_font_size = '12pt'\np.title.text_font_style = \"bold\"\n\np.hbar(\n        y='index',\n        right='TeamName',\n        height=0.8,\n        color = 'blue',\n        line_color=\"black\", \n        line_width=1,\n        fill_alpha=0.7,\n        source = source\n)\nshow(p)\n\n# data preparation\nlteam = mtourney_results.rename(columns={'LTeamID':'TeamID'})\nlost_team =  lteam.merge(mteams, on='TeamID')\nlost_team = lost_team.rename(columns={'TeamID':'LTeamID_X'})\ntemp = lost_team['TeamName'].value_counts().head(15).reset_index()\n\n# Create ColumnDataSource from data frame\nsource = ColumnDataSource(temp)\nlost_team_list = source.data['index'].tolist()\n\n# Add Plot\np = figure(\n    y_range = lost_team_list,\n    plot_width=600,\n    plot_height=320,\n    title=\"Most Tournament Lost since 1985\",\n    y_axis_label='Runner-Up',\n    tools=\"\"\n    \n)\np.title.text_font = 'helvetica'\np.title.text_font_size = '12pt'\np.title.text_font_style = \"bold\"\n\np.hbar(\n        y='index',\n        right='TeamName',\n        height=0.8,\n        color = 'orange',\n        line_color=\"black\", \n        line_width=1,\n        fill_alpha=0.7,\n        source = source\n)\n\nshow(p)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Which Team Wins And Lost The Most Championships?\n\n* DayNum=154 (Mon) - Round 6, otherwise known as \"national final\" or \"national championship\", to bring the tournament field from 2 teams to 1 champion team"},{"metadata":{"trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"#data preparation\nncaa_win_camp = win_team[win_team['DayNum'] ==154]['TeamName'].value_counts().reset_index()\n\n# Create ColumnDataSource from data frame\nsource = ColumnDataSource(ncaa_win_camp )\nwin_camp_list = source.data['index'].tolist()\n\n# Add Plot\np = figure(\n    y_range = win_camp_list,\n    plot_width=600,\n    plot_height=320,\n    title=\"Tournament Championship Wins since 1985\",\n    y_axis_label='Winners',\n    tools=\"\"\n    \n)\np.title.text_font = 'helvetica'\np.title.text_font_size = '12pt'\np.title.text_font_style = \"bold\"\n\np.hbar(\n        y='index',\n        right='TeamName',\n        height=0.8,\n        color = 'blue',\n        line_color=\"black\", \n        line_width=1,\n        fill_alpha=0.7,\n        source = source\n)\n\nshow(p)\n\n#data preparation\nncaa_lost_camp  = lost_team[lost_team['DayNum']==154]['TeamName'].value_counts().reset_index()\n\n# Create ColumnDataSource from data frame\nsource = ColumnDataSource(ncaa_lost_camp)\nlost_camp_list = source.data['index'].tolist()\n\n# Add Plot\np = figure(\n    y_range = lost_camp_list,\n    plot_width=600,\n    plot_height=300,\n    title=\"Tournament Championship Lost since 1985\",\n    y_axis_label='Runner-Up',\n    tools=\"\"\n    \n)\np.title.text_font = 'helvetica'\np.title.text_font_size = '12pt'\np.title.text_font_style = \"bold\"\n\np.hbar(\n        y='index',\n        right='TeamName',\n        height=0.8,\n        color = 'orange',\n        line_color=\"black\", \n        line_width=1,\n        fill_alpha=0.7,\n        source = source\n)\n\nshow(p)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"The major programs certainly fill out the top schools when it comes to championship games, and none more than Duke. Duke won 97 times and runner-up 29 times. Also **Duke** wins 5 Championship with 5 runner-up  this results are shows that who is the champion of the games so far. "},{"metadata":{},"cell_type":"markdown","source":"## Which Team Seed And Conference Wins The Most Championships?"},{"metadata":{"trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"mtourney_seed['Region'] = mtourney_seed['Seed'].apply(lambda x: x[0][:1])\nmtourney_seed['Seed'] = mtourney_seed['Seed'].apply(lambda x: int(x[1:3]))","execution_count":null,"outputs":[]},{"metadata":{"_kg_hide-input":true,"trusted":true},"cell_type":"code","source":"#data preparation\nseed_win_team =  win_team.merge(mtourney_seed, on=['TeamID','Season'])\nseed_win_camp = seed_win_team[seed_win_team['DayNum'] ==154]['Seed'].value_counts().reset_index()\n\nseed = list(seed_win_camp['index'].astype(str))\ncount =  list(seed_win_camp['Seed'])\n\n#plot\ndot = figure(title=\"Seeds With The Most Titles since 1985\", tools=\"\", toolbar_location=None,\n            y_range=seed, x_range=[0,25], plot_width=600, plot_height=400,)\ndot.title.text_font = 'helvetica'\ndot.title.text_font_size = '12pt'\ndot.title.text_font_style = \"bold\"\n\ndot.segment(0, seed, count, seed, line_width=3, line_color=\"green\", )\ndot.circle(count, seed, size=15, fill_color=\"orange\", line_color=\"green\", line_width=3, )\n\nshow(dot)\n#----------------------------------------\nfrom bokeh.models import LabelSet\n#data preparation\nteam_conf =  team_conference.merge(conference, on='ConfAbbrev') \nconf_win_team =  win_team.merge(team_conf, on=['TeamID', 'Season'])\nconf_win_camp = conf_win_team[conf_win_team['DayNum']==154]['Description'].value_counts().reset_index()\n\n# Create ColumnDataSource from data frame\nsource = ColumnDataSource(conf_win_camp)\nconf_team_list = source.data['index'].tolist()\n\n# Add Plot\np = figure(\n    y_range = conf_team_list,\n    plot_width=800,\n    plot_height=400,\n    title=\"'NCAA Championships by Conference 1985\",\n    tools=\"\"\n    \n)\np.title.text_font = 'helvetica'\np.title.text_font_size = '12pt'\np.title.text_font_style = \"bold\"\n\np.hbar(\n        y='index',\n        right='Description',\n        height=0.8,\n        color = 'green',\n        line_color=\"black\", \n        line_width=1,\n        fill_alpha=0.7,\n        source = source\n)\nlabels = LabelSet(y='index', x='Description', text='Description', x_offset=-18, y_offset=-5.5, source=source, render_mode='canvas')\np.add_layout(labels)\nshow(p)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Since the tournament was expanded to 64 teams in 1985, No. 1 seeds have won the tournament 21 times. A No. 2 seed has won the tournament five times while the third seed has won four times. Interestingly, the number 5 seed has not won a tournament in the period analysed. The “seed of death” perhaps.**Atlantic Coast Conference** have produced the most champions and won 11 championships since 1985.\n\nLet's look on the conferences and their teams who contributed in the tournament"},{"metadata":{"_kg_hide-input":true,"trusted":true},"cell_type":"code","source":"conf_win_team = conf_win_team[conf_win_team['DayNum']==154]\ntemp_df = pd.crosstab(conf_win_team.Description, conf_win_team.TeamName)\nplt.rcParams['figure.figsize'] = (8,8)\nsns.set_style(\"white\")\nsns.heatmap(temp_df, cmap=\"YlGnBu\", annot=True,fmt='g', cbar=False)\nplt.xlabel('Team Name',fontsize = 20)\nplt.ylabel('Conference',fontsize = 20)\nplt.title('Conference Matchups With Teams NCAA Tournament', fontsize = 20)\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Duke and North Carolina members of the Atlantic Coast Conference (ACC) are conbributed the most championships."},{"metadata":{},"cell_type":"markdown","source":"# Data Section 2 - Team Box Scores\nThis section provides game-by-game stats at a team level (free throws attempted, defensive rebounds, turnovers, etc.) for all regular season, conference tournament, and NCAA® tournament games since the 2002-03 season.\n\nData Section 2 - Team Box Scores ==> [File descriptions](https://www.kaggle.com/c/march-madness-analytics-2020/data)\n"},{"metadata":{"trusted":true},"cell_type":"code","source":"tour_results = pd.read_csv('../input/march-madness-analytics-2020/2020DataFiles/2020-Mens-Data/MDataFiles_Stage1/MNCAATourneyDetailedResults.csv')\nseason_results = pd.read_csv('../input/march-madness-analytics-2020/2020DataFiles/2020-Mens-Data/MDataFiles_Stage1/MRegularSeasonDetailedResults.csv')\nseason_results.head()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Indicators of Regular Season Success\nLet’s now turn to the regular season game statistics. We are interested in knowing how certain statistics correlate with winning vs losing. We will take the regular season detail and first convert it to a more ‘long’ format with only 1 column of TeamIDs and a factor indicating whether that row corresponds to a win or a loss. Here I also add some additional game statistcs. These include field goal percentage, free throw percentage, offensive/defensive rebounding efficiency, and possessions. The feature-engineering code from Laksan Nathan’s [kernel here](https://www.kaggle.com/lnatml/feature-engineering-with-advanced-stats) .\n* **For More Info visit [stats.nba.com](https://stats.nba.com/help/glossary/)**"},{"metadata":{"trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"#Points Winning/Losing Team\nseason_results['WPts'] = season_results.apply(lambda row: 2*row.WFGM + row.WFGM3 + row.WFTM, axis=1)\nseason_results['LPts'] = season_results.apply(lambda row: 2*row.LFGM + row.LFGM3 + row.LFTM, axis=1)\n\n#Calculate Winning/losing Team Possesion Feature\nwPos = season_results.apply(lambda row: 0.96*(row.WFGA + row.WTO + 0.44*row.WFTA - row.WOR), axis=1)\nlPos = season_results.apply(lambda row: 0.96*(row.LFGA + row.LTO + 0.44*row.LFTA - row.LOR), axis=1)\n#two teams use almost the same number of possessions in a game\n#(plus/minus one or two - depending on how quarters end)\n#so let's just take the average\nseason_results['Pos'] = (wPos+lPos)/2\n\n'''Advanced Metrics'''\n#Offensive efficiency (OffRtg) = 100 x (Points / Possessions)\nseason_results['WOffRtg'] = season_results.apply(lambda row: 100 * (row.WPts / row.Pos), axis=1)\nseason_results['LOffRtg'] = season_results.apply(lambda row: 100 * (row.LPts / row.Pos), axis=1)\n\n#Defensive efficiency (DefRtg) = 100 x (Opponent points / Opponent possessions)\nseason_results['WDefRtg'] = season_results.LOffRtg\nseason_results['LDefRtg'] = season_results.WOffRtg\n\n#Net Rating = Off.Rtg - Def.Rtg\nseason_results['WNetRtg'] = season_results.apply(lambda row:(row.WOffRtg - row.WDefRtg), axis=1)\nseason_results['LNetRtg'] = season_results.apply(lambda row:(row.LOffRtg - row.LDefRtg), axis=1)\n                         \n#Assist Ratio : Percentage of team possessions that end in assists\nseason_results['WAstR'] = season_results.apply(lambda row: 100 * row.WAst / (row.WFGA + 0.44*row.WFTA + row.WAst + row.WTO), axis=1)\nseason_results['LAstR'] = season_results.apply(lambda row: 100 * row.LAst / (row.LFGA + 0.44*row.LFTA + row.LAst + row.LTO), axis=1)\n\n#Turnover Ratio: Number of turnovers of a team per 100 possessions used.\n#(TO * 100) / (FGA + (FTA * 0.44) + AST + TO)\nseason_results['WTOR'] = season_results.apply(lambda row: 100 * row.WTO / (row.WFGA + 0.44*row.WFTA + row.WAst + row.WTO), axis=1)\nseason_results['LTOR'] = season_results.apply(lambda row: 100 * row.LTO / (row.LFGA + 0.44*row.LFTA + row.LAst + row.LTO), axis=1)\n\n#The Shooting Percentage : Measure of Shooting Efficiency (FGA/FGA3, FTA)\nseason_results['WTSP'] = season_results.apply(lambda row: 100 * row.WPts / (2 * (row.WFGA + 0.44 * row.WFTA)), axis=1)\nseason_results['LTSP'] = season_results.apply(lambda row: 100 * row.LPts / (2 * (row.LFGA + 0.44 * row.LFTA)), axis=1)\n\n#eFG% : Effective Field Goal Percentage adjusting for the fact that 3pt shots are more valuable \nseason_results['WeFGP'] = season_results.apply(lambda row:(row.WFGM + 0.5 * row.WFGM3) / row.WFGA, axis=1)      \nseason_results['LeFGP'] = season_results.apply(lambda row:(row.LFGM + 0.5 * row.LFGM3) / row.LFGA, axis=1)   \n\n#FTA Rate : How good a team is at drawing fouls.\nseason_results['WFTAR'] = season_results.apply(lambda row: row.WFTA / row.WFGA, axis=1)\nseason_results['LFTAR'] = season_results.apply(lambda row: row.LFTA / row.LFGA, axis=1)\n                         \n#OREB% : Percentage of team offensive rebounds\nseason_results['WORP'] = season_results.apply(lambda row: row.WOR / (row.WOR + row.LDR), axis=1)\nseason_results['LORP'] = season_results.apply(lambda row: row.LOR / (row.LOR + row.WDR), axis=1)\n\n#DREB% : Percentage of team defensive rebounds\nseason_results['WDRP'] = season_results.apply(lambda row: row.WDR / (row.WDR + row.LOR), axis=1)\nseason_results['LDRP'] = season_results.apply(lambda row: row.LDR / (row.LDR + row.WOR), axis=1)                                      \n\n#REB% : Percentage of team total rebounds\nseason_results['WRP'] = season_results.apply(lambda row: (row.WDR + row.WOR) / (row.WDR + row.WOR + row.LDR + row.LOR), axis=1)\nseason_results['LRP'] = season_results.apply(lambda row: (row.LDR + row.LOR) / (row.WDR + row.WOR + row.LDR + row.LOR), axis=1) ","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### Distribution of Statistics for Winning and Losing teams.\nNow let’s take a look at the distributions of these statistics for winning and losing teams."},{"metadata":{"_kg_hide-input":true,"trusted":true},"cell_type":"code","source":"from matplotlib.font_manager import FontProperties\nfont = FontProperties()\nfont.set_family('serif')\nsns.set_style(\"whitegrid\")\nf, axes = plt.subplots (5,2, figsize=(10,20))  \n\nax1 = sns.kdeplot(season_results['WPts'], shade = True,ax=axes[0,0], label=\"W\",color = 'k')\nax1 = sns.kdeplot(season_results['LPts'], shade = True,ax=axes[0,0], label=\"L\", color = 'm')\nax1.set(xlabel='Points')\naxes[0,0].set_title('Macth Points',loc='left',fontsize=15, FontProperties=font, fontweight='bold')\nplt.setp(ax1.get_legend().get_texts(), fontsize='10')\n\nax2 = sns.kdeplot(wPos, shade = True,ax=axes[0,1], label=\"W\",color = 'k')\nax2 = sns.kdeplot(lPos, shade = True,ax=axes[0,1], label=\"L\", color = 'm')\nax2.set(xlabel='Possesion Points')\naxes[0,1].set_title('Team Possesion',loc='left',fontsize=15, FontProperties=font, fontweight='bold')\nplt.setp(ax2.get_legend().get_texts(), fontsize='10')\n\nax3 = sns.kdeplot(season_results['WOffRtg'], shade = True,ax=axes[1,0], label=\"W\",color = 'k')\nax3 = sns.kdeplot(season_results['LOffRtg'], shade = True,ax=axes[1,0], label=\"L\", color = 'm')\nax3.set(xlabel='Offensive efficiency')\naxes[1,0].set_title('Offensive Efficiency',loc='left',fontsize=15, FontProperties=font, fontweight='bold')\nplt.setp(ax3.get_legend().get_texts(), fontsize='10')\n\nax4 = sns.kdeplot(season_results['WDefRtg'], shade = True,ax=axes[1,1], label=\"W\",color = 'k')\nax4 = sns.kdeplot(season_results['LDefRtg'], shade = True,ax=axes[1,1], label=\"L\", color = 'm')\nax4.set(xlabel='Defensive efficiency')\naxes[1,1].set_title('Defensive Efficiency',loc='left',fontsize=15, FontProperties=font, fontweight='bold')\nplt.setp(ax4.get_legend().get_texts(), fontsize='10')\n\nax5 = sns.kdeplot(season_results['WAstR'], shade = True,ax=axes[2,0], label=\"W\",color = 'k')\nax5 = sns.kdeplot(season_results['LAstR'], shade = True,ax=axes[2,0], label=\"L\", color = 'm')\nax5.set(xlabel='Assist')\naxes[2,0].set_title('Assist Ratio',loc='left',fontsize=15, FontProperties=font, fontweight='bold')\nplt.setp(ax5.get_legend().get_texts(), fontsize='10')\n\nax6 = sns.kdeplot(season_results['WTOR'], shade = True,ax=axes[2,1], label=\"W\",color = 'k')\nax6 = sns.kdeplot(season_results['LTOR'], shade = True,ax=axes[2,1], label=\"L\", color = 'm')\nax6.set(xlabel='Turnover')\naxes[2,1].set_title('Turnover Ratio',loc='left',fontsize=15, FontProperties=font, fontweight='bold')\nplt.setp(ax6.get_legend().get_texts(), fontsize='10')\n\nax7 = sns.kdeplot(season_results['WTSP'], shade = True,ax=axes[3,0], label=\"W\",color = 'k')\nax7 = sns.kdeplot(season_results['LTSP'], shade = True,ax=axes[3,0], label=\"L\", color = 'm')\nax7.set(xlabel='Shooting')\naxes[3,0].set_title('Goal Shooting Percentage',loc='left',fontsize=15, FontProperties=font, fontweight='bold')\nplt.setp(ax7.get_legend().get_texts(), fontsize='10')\n\nax8 = sns.kdeplot(season_results['WeFGP'], shade = True,ax=axes[3,1], label=\"W\",color = 'k')\nax8 = sns.kdeplot(season_results['LeFGP'], shade = True,ax=axes[3,1], label=\"L\", color = 'm')\nax8.set(xlabel='3pt Goal Shots %')\naxes[3,1].set_title('3pt Goal Shots',loc='left',fontsize=15, FontProperties=font, fontweight='bold')\nplt.setp(ax8.get_legend().get_texts(), fontsize='10')\n\nax9 = sns.kdeplot(season_results['WORP'], shade = True,ax=axes[4,0], label=\"W\",color = 'k')\nax9 = sns.kdeplot(season_results['LORP'], shade = True,ax=axes[4,0], label=\"L\", color = 'm')\nax9.set(xlabel='Offensive %')\naxes[4,0].set_title('Offensive Rebounding  Efficiency',loc='left',fontsize=15, FontProperties=font, fontweight='bold')\nplt.setp(ax9.get_legend().get_texts(), fontsize='10')\n\nax10 = sns.kdeplot(season_results['WDRP'], shade = True,ax=axes[4,1], label=\"W\",color = 'k')\nax10 = sns.kdeplot(season_results['LDRP'], shade = True,ax=axes[4,1], label=\"L\", color = 'm')\nax10.set(xlabel='Defensive %')\naxes[4,1].set_title('Defensive Rebounding Efficiency',loc='left',fontsize=15, FontProperties=font, fontweight='bold')\nplt.setp(ax10.get_legend().get_texts(), fontsize='10')\n\nplt.subplots_adjust(wspace=0.4)\nplt.subplots_adjust(hspace=0.4)\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Unsurprisingly, we see that winning teams tend to have a higher mean (or lower in the case of turnover) in pretty much every metric. But possession between the two teams use almost the same number of possessions points in a game.\n\nWe don’t have final game statistics until we have the game result, so we obviously can’t use these statistics in this form to predict the winners of tournament matchups. However, we can use regular season aggregate statistics to know the Correlation between Absolute Variable And Relative (statistics) Variables and to predict the winner in tournament matchups. Let’s take a look at that next. "},{"metadata":{},"cell_type":"markdown","source":"### Correlation between Absolute Variable And Relative Variables of Winning and Losing teams.\nNow let’s take a look at the Correlation between Absolute Variable And Relative (statistics) Variables of Winning and Losing teams. "},{"metadata":{"_kg_hide-input":true,"trusted":true},"cell_type":"code","source":"sns.set_style(\"white\")\nf,axes = plt.subplots(1,4, figsize=(12,12)) \n\nWabsolute_values = season_results[['WScore','WFGM', 'WFGA', 'WFGM3', 'WFGA3', 'WFTM', \n                          'WFTA', 'WOR', 'WDR','WAst', 'WTO', 'WStl', 'WBlk', 'WPF']]\nWrelative_values = season_results[['WPts','Pos', 'WOffRtg', 'WDefRtg', 'WNetRtg','WAstR', \n                          'WTOR', 'WTSP', 'WeFGP', 'WFTAR', 'WORP', 'WDRP', 'WRP']]\nLabsolute_values = season_results[['LScore','LFGM', 'LFGA', 'LFGM3', 'LFGA3','LFTM', \n                                   'LFTA', 'LOR', 'LDR', 'LAst', 'LTO', 'LStl', 'LBlk', 'LPF',]]\nLrelative_values = season_results[['LPts','Pos', 'LOffRtg', 'LDefRtg', 'LNetRtg','LAstR', \n                          'LTOR', 'LTSP', 'LeFGP', 'LFTAR', 'LORP', 'LDRP', 'LRP']]\n\ncorr1 = Wabsolute_values.corr()\nmask = np.zeros_like(corr1, dtype=np.bool)\nmask[np.triu_indices_from(mask)] = True\nax1 = sns.heatmap(corr1, mask=mask, cmap=\"RdGy\",linewidths=.5, \n                  vmin=0, vmax=1,ax=axes[0],cbar=False,square=True)\nax1.tick_params(axis='both', which='major', labelsize=8) \nax1.set_title(\"Winning Absolute Variables\", fontsize=8,\n              FontProperties=font, fontweight='bold')\n\n\ncorr2 = Wrelative_values.corr()\nmask = np.zeros_like(corr2, dtype=np.bool)\nmask[np.triu_indices_from(mask)] = True\nax2 = sns.heatmap(corr2, mask=mask, cmap=\"RdGy\",linewidths=.5, \n                  vmin=0, vmax=1,ax=axes[1],cbar=False,square=True)\nax2.tick_params(axis='both', which='major', labelsize=8) \nax2.set_title(\"Winning Relative Variables\", fontsize=8,\n             FontProperties=font, fontweight='bold')\n\n\ncorr3 = Labsolute_values.corr()\nmask = np.zeros_like(corr3, dtype=np.bool)\nmask[np.triu_indices_from(mask)] = True\nax3 = sns.heatmap(corr3, mask=mask, cmap=\"RdGy\",linewidths=.5, \n                  vmin=0, vmax=1,ax=axes[2],cbar=False,square=True)\nax3.tick_params(axis='both', which='major', labelsize=8) \nax3.set_title(\"Losing Absolute Variables\", fontsize=8,\n             FontProperties=font, fontweight='bold')\n\n\ncorr4 = Lrelative_values.corr()\nmask = np.zeros_like(corr4, dtype=np.bool)\nmask[np.triu_indices_from(mask)] = True\nax4 = sns.heatmap(corr4, mask=mask, cmap=\"RdGy\",linewidths=.5, \n                  vmin=0, vmax=1,ax=axes[3],square=True, cbar = False) \nax4.tick_params(axis='both', which='major', labelsize=8) \nax4.set_title(\"Losing Relative Variables\", fontsize=8,\n             FontProperties=font, fontweight='bold')\n\n\nplt.subplots_adjust(hspace=1)\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"In the above plot, we can see that which variable is more correlated with winning score, winning points, losing score and losing points. such as winning score more correlated with WTO (turnovers committed), Wstl(steals).\n**Note:** Darker color show more correlation and light color show less correlation."},{"metadata":{},"cell_type":"markdown","source":"### Relationship between Tournament Wins(tW) And Regular Season Wins(rsW)\nHow deep a team goes in the tournament would be regular season wins. Let’s see how regular season wins relate to tournament progress each year.\n**Note:**The Tournament \"play-in\" games are on days 134/135, Selection Sunday is on day 132, the final day of the regular season is also day 132, and so on.\n"},{"metadata":{"trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"win_s = season_results.groupby(['Season','WTeamID'])['WTeamID'].count().to_frame('rsW')\nwin_t = tour_results.groupby(['Season','WTeamID'])['WTeamID'].count().to_frame('tW')\nwin_team = win_s.merge(win_t,on=['Season','WTeamID']).reset_index()\n\nsns.set_style(\"whitegrid\")\nax=sns.lmplot(x='rsW' , y='tW', data=win_team, col='Season', col_wrap=4,line_kws={'color': 'black'},)\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"In nearly every year, tournament wins is positively correlated with regular season wins.Let’s do something similar to see if average scores during regular season are associated with better tournament progress."},{"metadata":{"_kg_hide-input":true,"trusted":true},"cell_type":"code","source":"w_season_results = season_results.rename(columns={'WTeamID':'TeamID'}) # rename the WteamID as TeamID for merge with mteams dataframe\nst_seed_win_team = w_season_results.merge(mtourney_seed, on=['TeamID','Season'])\nst_seed_win_team = st_seed_win_team.rename(columns={'TeamID':'WTeamID'})\nseed_win_team = st_seed_win_team.merge(win_t,on=['Season','WTeamID']).reset_index()\n\nsns.set_style(\"whitegrid\")\nplt.figure(figsize=(15,10))\nax=sns.regplot(x='Seed' , y='tW', marker='o', data=seed_win_team, line_kws={'color': 'black'})\nax.set_title('Tournament Wins by Seed',loc='left',fontsize=30, FontProperties=font, fontweight='bold')\nax.set_xlabel('Seed',fontsize=12)\nax.set_ylabel('Tournament Wins', fontsize=12)\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"I’ve introduced some jiter to this plot to avoid overplotting. It exhibits a strong negative relationship between seed and tournament progress - the lower a team’s seed, the deeper they go into the tournament (as measured by tournament wins). We see that a 16 seed has never made it past the first round of the tournament. From the plot we can also determine that the lowest seed to ever win the tournament was a number 8. "},{"metadata":{"trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"tw_season_results = season_results.merge(win_t,on=['Season','WTeamID']).reset_index()\ntemp = tw_season_results[tw_season_results['tW'] >=4]\n\nh1 = sns.jointplot(x=\"WFGM\", y=\"WFTA\", data=temp,\n                  kind=\"scatter\",color='k',s=10,height=6)\nh1.ax_marg_x.hist(temp['WFGM'], color=\"steelblue\", alpha=.6)\nh1.ax_marg_y.hist(temp['WFTA'], color=\"steelblue\", alpha=.6,\n                     orientation=\"horizontal\")\nh1.fig.suptitle('Regular Season Shooting Performance of Tournament Teams',fontsize=20, FontProperties=font, fontweight='bold')\nh1.set_axis_labels('Field Goals','Free Throws Attempted', fontsize=12)\nh1.fig.subplots_adjust(top=0.9)\n\nh2 = sns.jointplot(x=\"WFGM\", y=\"WAst\", data=temp,\n                  kind=\"scatter\",color='k',s=10,height=6)\nh2.ax_marg_x.hist(temp['WFGM'], color=\"darkred\", alpha=.6)\nh2.ax_marg_y.hist(temp['WAst'], color=\"darkred\", alpha=.6,\n                     orientation=\"horizontal\")\nh2.fig.suptitle('Regular Season Assist Performance of Tournament Teams',fontsize=20, FontProperties=font, fontweight='bold')\nh2.set_axis_labels('Field Goals','Assist', fontsize=12)\nh2.fig.subplots_adjust(top=0.9)\n\nh3 = sns.jointplot(x=\"WFGM\", y=\"WStl\", data=temp,\n                  kind=\"scatter\",color='k',s=10,height=6)\nh3.ax_marg_x.hist(temp['WFGM'], color=\"darkgreen\", alpha=.6)\nh3.ax_marg_y.hist(temp['WStl'], color=\"darkgreen\", alpha=.6,\n                     orientation=\"horizontal\")\nh3.fig.suptitle('Regular Season Steals Performance of Tournament Teams',fontsize=20, FontProperties=font, fontweight='bold')\nh3.set_axis_labels('Field Goals','Steal', fontsize=12)\nh3.fig.subplots_adjust(top=0.9)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Interestingly in terms of shooting and stealing, there does not seem to be much of a difference between teams that make the Final Four and the rest of the tournament field in terms of their regular season performance; however it is hard to tell from this plot type. "},{"metadata":{},"cell_type":"markdown","source":"## <font color='lime'>Give me your feedback and if you find my kernel helpful please UPVOTE will be appreciated</font>"}],"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"pygments_lexer":"ipython3","nbconvert_exporter":"python","version":"3.6.4","file_extension":".py","codemirror_mode":{"name":"ipython","version":3},"name":"python","mimetype":"text/x-python"}},"nbformat":4,"nbformat_minor":1}