{"cells":[{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"# This Python 3 environment comes with many helpful analytics libraries installed\n# It is defined by the kaggle/python docker image: https://github.com/kaggle/docker-python\n# For example, here's several helpful packages to load in \n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport gc\nfrom scipy.stats import skew\nimport re\n# Input data files are available in the \"../input/\" directory.\n# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\n\nimport os\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n\n# Any results you write to the current directory are saved as output.","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"teams = pd.read_csv('/kaggle/input/google-cloud-ncaa-march-madness-2020-division-1-mens-tournament/MDataFiles_Stage1/MTeams.csv')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def get_team_dict(df):\n    group = df.groupby(['TeamID','TeamName']).size().reset_index()\n    team_ids = list(group['TeamID'])\n    team_names = list(group['TeamName'])\n    return dict((x,y) for x,y in list(zip(team_ids, team_names)))\n\nteam_dict = get_team_dict(teams)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"players = pd.read_csv('/kaggle/input/google-cloud-ncaa-march-madness-2020-division-1-mens-tournament/MPlayers.csv')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def get_player_dict(df):\n    lol = players.groupby(['PlayerID','LastName','FirstName']).size().reset_index()\n    lol['Name'] = lol['FirstName'] + ['_']*lol.shape[0] + lol['LastName']\n    player_ids = list(lol['PlayerID'])\n    player_names = list(lol['Name'])\n    return dict((x,y) for x,y in list(zip(player_ids, player_names)))\n\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"results = pd.read_csv('/kaggle/input/google-cloud-ncaa-march-madness-2020-division-1-mens-tournament/MDataFiles_Stage1/MNCAATourneyDetailedResults.csv')\nresults = results.drop('WLoc', axis = 1) #useless col (1115 'N' values)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def plot_kde(results, col):\n    \n    win_col = 'W' + col\n    lost_col = \"L\" + col\n    \n    plt.figure(figsize = (12,5))\n    plt.title(\"Team avg per match \" + col)\n    sns.kdeplot(results[win_col])\n    sns.kdeplot(results[lost_col])\n    \nw_l_cols = [re.sub('(L|W){1}', \"\", i) for i in results.columns if re.match('[LW]{1}', i)]\nstat_cols = list(set(w_l_cols))\nstat_cols.remove('TeamID')\n\nfor col in stat_cols:\n    plot_kde(results, col)\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def plot_kde(results, col):\n    \n    win_col = 'W' + col\n    lost_col = \"L\" + col\n    \n    plt.figure(figsize = (12,5))\n    sns.kdeplot(results[win_col])\n    sns.kdeplot(results[lost_col])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"team_dict = get_team_dict(teams)\nresults['WTeam'] = results.WTeamID.map(lambda x:team_dict[x])\nresults['LTeam'] = results.LTeamID.map(lambda x:team_dict[x])\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def basic_eda(train):\n    tr_nulls = train.isnull().sum()\n    for col in train.columns[1:]:\n        if train[col].dtype != object:\n            plt.figure(figsize = (12,4))\n            plt.title('%s has %s nulls and %s nunique, %s dtype, %s skew' %(col,tr_nulls[col], train[col].nunique(), train[col].dtype, skew(train[col])))\n            sns.distplot(train[col].dropna())\n        if train[col].dtype == object:\n            print ('%s has %s nuniq' %(col, train[col].nunique()))\n            print (train[col].unique()[:10])","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"ev_16 = pd.read_csv('/kaggle/input/google-cloud-ncaa-march-madness-2020-division-1-mens-tournament/MEvents2016.csv')\nev_17 = pd.read_csv('/kaggle/input/google-cloud-ncaa-march-madness-2020-division-1-mens-tournament/MEvents2017.csv')\nev_18 = pd.read_csv('/kaggle/input/google-cloud-ncaa-march-madness-2020-division-1-mens-tournament/MEvents2018.csv')\nev_19 = pd.read_csv('/kaggle/input/google-cloud-ncaa-march-madness-2020-division-1-mens-tournament/MEvents2019.csv')\nplayers = pd.read_csv('/kaggle/input/google-cloud-ncaa-march-madness-2020-division-1-mens-tournament/MPlayers.csv')\n\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"ev_full = pd.concat([ev_16, ev_17, ev_18, ev_19], ignore_index = True)\ndel ev_16, ev_17, ev_18, ev_19","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"ev_full['win_bool'] = ev_full['WTeamID'] - ev_full['EventTeamID']\nev_full['win_bool'] = ev_full['win_bool'].map(lambda x: 1 if x == 0 else 0)\n\nev_full['event_name'] = ev_full['EventType'] + ['_'] * ev_full.shape[0] + ev_full['EventSubType']\n\nev_full.loc[ev_full['event_name'] == 'jumpb_start', 'EventTeamID'] = 1\n\n#np.where to replace event_names whose EventTeamID == 0\na = np.array(['id0_error'] * ev_full.shape[0]) #error arr\nb = np.array(list(ev_full['EventTeamID']))\nc = np.array(list(ev_full['event_name']))\nev_full['event_name'] = np.where(b == 0, a, c)\n\n#ignore player id 0 when eda player stats","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"ev_full = ev_full.sort_values(['Season','DayNum','WTeamID','WCurrentScore','ElapsedSeconds']).reset_index().drop('index', axis = 1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"val_cnts = ev_full['event_name'].value_counts()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"val_cnts[-30:-20]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"val_cnts[:45]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"win = ev_full[ev_full.win_bool == 1].groupby(['Season',\"DayNum\", \"WTeamID\", \"event_name\"]).size()\nlost = ev_full[ev_full.win_bool == 0].groupby(['Season',\"DayNum\", \"WTeamID\", \"event_name\"]).size()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"lol = ev_full.iloc[7897547:7897557, :]\nlol.head(20)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"lol = ev_full.iloc[7904503:7904509, :]\nlol.head(20)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"ev_full[ev_full.event_name == \"miss1_1of3\"]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"\nevname = 'made2_stepb'\nplt.figure(figsize = (15,4))\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"for event in ['s':\n    if match_group[match_group.event_name == event]['ev_count'].nunique() > 10:\n    \n        plt.figure(figsize = (10,4))\n        plt.title(event)\n        win_ax = sns.kdeplot(match_group[match_group.win_bool == 0][match_group.event_name == event].rename(columns = {'ev_count':'lost'})['lost'].dropna())\n    \n        lost_ax = sns.kdeplot(match_group[match_group.win_bool == 1][match_group.event_name == event].rename(columns = {'ev_count':'won'})['won'].dropna()) ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"ev_full[ev_full.event_name == 'jumpb_won']","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"ev_name = 'jumpb_won'\n\nlol_win = ev_full[ev_full.win_bool == 1].groupby(['Season','DayNum','WTeamID','event_name']).size().reset_index()\nlol_lost = ev_full[ev_full.win_bool == 0].groupby(['Season','DayNum','WTeamID','event_name']).size().reset_index()\nlol_win.columns = ['Season', 'DayNum', 'WTeamID', 'event_name', 'win_count']\nlol_lost.columns = ['Season', 'DayNum', 'WTeamID', 'event_name', 'lost_count']","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"for i in lol_win.event_name.unique():\n    if 'jumpb' in i:\n        print (i)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"ev_name = 'reb_def'","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"lol_lost[lol_lost.event_name == ev_name]['lost_count'].value_counts()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"lol_win[lol_win.event_name == ev_name]['win_count'].value_counts()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"ev_name = 'made2_stepb'\n\nplt.figure(figsize = (15,6))\nsns.distplot(lol_win[lol_win.event_name == ev_name]['win_count'])\nsns.plot(lol_lost[lol_lost.event_name == ev_name]['lost_count'])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"year = 2017\ncount_num = 15\n\nlol_win = ev_full[ev_full.Season == year][ev_full.win_bool == 1].groupby(['DayNum','WTeamID','event_name'])size().reset_index()\nlol_lost = ev_full[ev_full.Season == year][ev_full.win_bool == 0].groupby(['DayNum','WTeamID','event_name']).size().reset_index()\n\nwin1 = lol_win.groupby('event_name')['count'].mean().sort_values(ascending = False).reset_index()\nlost1 = lol_lost.groupby('event_name')['count'].mean().sort_values(ascending = False).reset_index()\n\nwin_top = win1.head(count_num)\nlost_top = lost1.head(count_num)\n\nplt.figure(figsize = (20,6))\n\nplt.subplot(1,2,1)\nplt.title('win top %s of %s' %(count_num, year))\nsns.barplot(x = 'event_name', y = 'count', data = win_top)\nplt.xticks(rotation = 45)\n\nplt.subplot(1,2,2)\nplt.title('lost top %s of %s' %(count_num, year))\nsns.barplot(x = 'event_name', y = 'count', data = lost_top)\nplt.xticks(rotation = 45)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"markdown","source":"year = 2017\ncount_num = 15\n\nlol_win = ev_full[ev_full.Season == year][ev_full.win_bool == 1].groupby(['DayNum','WTeamID','event_name'])['ElapsedSeconds'].agg(['count','mean']).reset_index()\nlol_lost = ev_full[ev_full.Season == year][ev_full.win_bool == 0].groupby(['DayNum','WTeamID','event_name'])['ElapsedSeconds'].agg(['count','mean']).reset_index()\n\nwin1 = lol_win.groupby('event_name')['count'].mean().sort_values(ascending = False).reset_index()\nlost1 = lol_lost.groupby('event_name')['count'].mean().sort_values(ascending = False).reset_index()\n\nwin_top = win1.head(count_num)\nlost_top = lost1.head(count_num)\n\nplt.figure(figsize = (20,6))\n\nplt.subplot(1,2,1)\nplt.title('win top %s of %s' %(count_num, year))\nsns.barplot(x = 'event_name', y = 'count', data = win_top)\nplt.xticks(rotation = 45)\n\nplt.subplot(1,2,2)\nplt.title('lost top %s of %s' %(count_num, year))\nsns.barplot(x = 'event_name', y = 'count', data = lost_top)\nplt.xticks(rotation = 45)"},{"metadata":{"trusted":true},"cell_type":"code","source":"full_diff_df = pd.DataFrame({'event_name':list(ev_full.event_name.unique())})\n\n\nfor year in [2016,2017,2018,2019]:\n\n    lol_win = ev_full[ev_full.Season == year][ev_full.win_bool == 1].groupby(['DayNum','WTeamID','event_name'])['ElapsedSeconds'].agg(['count','mean']).reset_index()\n    lol_lost = ev_full[ev_full.Season == year][ev_full.win_bool == 0].groupby(['DayNum','WTeamID','event_name'])['ElapsedSeconds'].agg(['count','mean']).reset_index()\n\n    win1 = lol_win.groupby('event_name')['count'].mean().sort_values(ascending = False).reset_index()\n    win1.columns = ['event_name', 'win_count']\n    lost1 = lol_lost.groupby('event_name')['count'].mean().sort_values(ascending = False).reset_index()\n    lost1.columns = ['event_name','lost_count']\n\n    diff_df = pd.merge(win1, lost1, how = 'left', on = 'event_name')\n    diff_df['diff'] = diff_df['win_count'] / diff_df['lost_count']\n    diff_df = diff_df[['event_name','diff']]\n    diff_df.columns = ['event_name', 'diff_' + str(year)]\n    \n    full_diff_df = pd.merge(full_diff_df, diff_df, how = 'left', on = 'event_name')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"event_names = full_diff_df.sort_values('diff_2017').head(23).event_name.unique()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"match_group = ev_full.groupby(['Season','DayNum','EventTeamID','event_name','win_bool'])['ElapsedSeconds'].count().reset_index()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"ev_full.columns","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"match_group.columns = ['Season', 'DayNum', 'EventTeamID', 'event_name', 'win_bool',\n       'ev_count']","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"match_group.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"for event in event_names:\n    if match_group[match_group.event_name == event]['ev_count'].nunique() > 20:\n    \n        plt.figure(figsize = (10,4))\n        plt.title(event)\n        win_ax = sns.kdeplot(match_group[match_group.win_bool == 0][match_group.event_name == event].rename(columns = {'ev_count':'lost'})['lost'].dropna())\n    \n        lost_ax = sns.kdeplot(match_group[match_group.win_bool == 1][match_group.event_name == event].rename(columns = {'ev_count':'won'})['won'].dropna())\n    \n    \n    \n    ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"match_group = ev_full.groupby(['Season','DayNum','WTeamID','LTeamID'])['']","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#all of the nan event_names only exists in 2019\nlol_list = list(lol[lol.diff_2016.isnull()].event_name)\nlol_list.remove(np.nan)\nev_full[ev_full.event_name.isin(lol_list)].Season.unique()\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"ev_full.isnull().sum()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"ev_full.EventSubType.unique()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"ev_full[ev_full.EventSubType == 'coate'].DayNum.unique()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"collapsed":true},"cell_type":"code","source":"ev_names = list(ev_full.event_name.unique())\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"ev_full.event_name.nunique()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"diff_df['diff'] = diff_df['win_count'] / diff_df['lost_count']\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"pd.DataFrame({'event_name':list(ev_full.event_name.unique())})","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"diff_df.sort_values('diff')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"lol_top = lol1.head(10)\nplt.figure()\nsns.barplot(x = 'event_name', y = 'count', data = lol_top)\nplt.xticks(rotation = 45)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"lol1.head(1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"lol.tail(3)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"for season in ev_full.Season.unique():\n    lol = ev_full[ev_full.Season == 2017].groupby(['event_name'])['win_bool'].agg(['count','mean']).sort_values('mean').reset_index()\n    lol['name_count'] = lol['event_name'] + ['_'].shape[0] + lol['count'].astype('str')\n    top10 = lol.tail(10)\n    bottom1","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"sample_df = pd.read_csv('/kaggle/input/google-cloud-ncaa-march-madness-2020-division-1-mens-tournament/MSampleSubmissionStage1_2020.csv')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"sample_df","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]}],"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}