{"cells":[{"metadata":{"trusted":true,"_uuid":"4eeb5bdfaf9f1b579bd4fa7537e87ca49d626363"},"cell_type":"code","source":"# import libraries\nimport warnings\nwarnings.simplefilter(action='ignore', category=FutureWarning)\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\n%matplotlib inline\npd.options.mode.chained_assignment = None  # default='warn'","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"d9e80e5f72a725802764b1998bef33d2e94df730"},"cell_type":"code","source":"# clean and merge NGS data for concussion plays\n# Read in 2016 NGS\ndf1 = pd.read_csv('../input/NFL-Punt-Analytics-Competition/NGS-2016-pre.csv')\ndf2 = pd.read_csv('../input/NFL-Punt-Analytics-Competition/NGS-2016-reg-wk1-6.csv')\ndf3 = pd.read_csv('../input/NFL-Punt-Analytics-Competition/NGS-2016-reg-wk7-12.csv')\ndf4 = pd.read_csv('../input/NFL-Punt-Analytics-Competition/NGS-2016-reg-wk13-17.csv')\ndf5 = pd.read_csv('../input/NFL-Punt-Analytics-Competition/NGS-2016-post.csv')\ndf1.dropna(subset=['GSISID'], inplace=True) \n\n# create list of applicable  2016(plays w/ concussions) values\nGame_Key_IDs = [5,21,29,45,54,60,144,149,189,218,231,234,266,274,280,280,281,289,296]\nPlay_IDs = [3129,2587,538,1212,1045,905,2342,3663,3509,3468,1976,3278,2902,3609,2918,3746,1526,2341,2667]\nGSISIDS = [31057,29343,31023,33121,32444,30786,32410,28128,27595,28987,32214,28620,23564,23742,32120,27654,28987,32007,32783,32482,31059,31941,28249,31756,\n29815,23259,29629,31950,32807,27860,31844,31785,32725,33127,30789,32998,32810]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"3958ab8fa32a0a84f49da91a1219579e64a7116c"},"cell_type":"code","source":"# set column origination\ndf1['Origin'] = 'NGS-2016-pre.csv'\ndf2['Origin'] = 'NGS-2016-reg-wk1-6.csv'\ndf3['Origin'] = 'NGS-2016-reg-wk7-12.csv'\ndf4['Origin'] = 'NGS-2016-reg-wk13-17.csv'\ndf5['Origin'] = 'NGS-2016-post.csv'","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"50b6e61f22912801d273e14175bc0646b24231d1"},"cell_type":"code","source":"# filter NGS datasets to only concussion plays\ndf1_filtered = df1[df1['GameKey'].isin(Game_Key_IDs) & df1['PlayID'].isin(Play_IDs) & df1['GSISID'].isin(GSISIDS)]\ndf1_filtered['GSISID'] = df1_filtered['GSISID'].astype('int64')\n\ndf2_filtered = df2[df2['GameKey'].isin(Game_Key_IDs) & df2['PlayID'].isin(Play_IDs) & df2['GSISID'].isin(GSISIDS)]\ndf2_filtered.dropna(subset=['GSISID'], inplace=True)\n\ndf3_filtered = df3[df3['GameKey'].isin(Game_Key_IDs) & df3['PlayID'].isin(Play_IDs) & df3['GSISID'].isin(GSISIDS)]\ndf3_filtered.dropna(subset=['GSISID'], inplace=True) \n\ndf4_filtered = df4[df4['GameKey'].isin(Game_Key_IDs) & df4['PlayID'].isin(Play_IDs) & df4['GSISID'].isin(GSISIDS)]\ndf4_filtered.dropna(subset=['GSISID'], inplace=True) \n\ndf5_filtered = df5[df5['GameKey'].isin(Game_Key_IDs) & df5['PlayID'].isin(Play_IDs) & df5['GSISID'].isin(GSISIDS)]\ndf5_filtered.dropna(subset=['GSISID'], inplace=True)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"01af127d0cc36ff12775cf65a083543ea657e1f3"},"cell_type":"code","source":"df2_filtered['GSISID'] = df2_filtered['GSISID'].astype('int64')\ndf3_filtered['GSISID'] = df3_filtered['GSISID'].astype('int64')\ndf4_filtered['GSISID'] = df4_filtered['GSISID'].astype('int64')\ndf5_filtered['GSISID'] = df5_filtered['GSISID'].astype('int64')\n\n# Build 2016 NGS dataframe\nNGS16_data = pd.concat([df1_filtered, df2_filtered, df3_filtered, df4_filtered, df5_filtered])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"1168e0e7a51890699cebf4f72f022ca34a2a9759"},"cell_type":"code","source":"# Read in 2017 NGS\ndf1 = pd.read_csv('../input/NFL-Punt-Analytics-Competition/NGS-2017-pre.csv')\ndf2 = pd.read_csv('../input/NFL-Punt-Analytics-Competition/NGS-2017-reg-wk1-6.csv')\ndf3 = pd.read_csv('../input/NFL-Punt-Analytics-Competition/NGS-2017-reg-wk7-12.csv')\ndf4 = pd.read_csv('../input/NFL-Punt-Analytics-Competition/NGS-2017-reg-wk13-17.csv')\ndf5 = pd.read_csv('../input/NFL-Punt-Analytics-Competition/NGS-2017-post.csv')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"17a3d9e328eec7cd548b91c2ec4ec92760fa90d5"},"cell_type":"code","source":"# set column origination\ndf1['Origin'] = 'NGS-2017-pre.csv'\ndf2['Origin'] = 'NGS-2017-reg-wk1-6.csv'\ndf3['Origin'] = 'NGS-2017-reg-wk7-12.csv'\ndf4['Origin'] = 'NGS-2017-reg-wk13-17.csv'\ndf5['Origin'] = 'NGS-2017-post.csv'\n\n# 2017 applicable (concussion plays) keys\nGame_Key_IDs = [357,364,364,384,392,397,399,414,448,473,506,553,567,585,585,601,607,618]\nPlay_IDs = [3630,2489,2764,183,1088,1526,3312,1262,2792,2072,1988,1683,1407,2208,733,602,978,2792]\nGSISIDS = [30171,31313,32323,33813,32615,32894,26035,33941,33838,29492,27060,32820,32403,33069,30384,33260,29793,31950,29384, 32851, 31930,33841,31999,31763,27442,31317,33445,25503,32891,24535,31697,32114,32677]\n\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"bc4dba29655ba5206ea7f6846f14242f9d2360bf"},"cell_type":"code","source":"df1_filtered = df1[df1['GameKey'].isin(Game_Key_IDs) & df1['PlayID'].isin(Play_IDs) & df1['GSISID'].isin(GSISIDS)]\ndf1_filtered.dropna(subset=['GSISID'], inplace=True) \ndf2_filtered = df2[df2['GameKey'].isin(Game_Key_IDs) & df2['PlayID'].isin(Play_IDs) & df2['GSISID'].isin(GSISIDS)]\ndf2_filtered.dropna(subset=['GSISID'], inplace=True) \ndf3_filtered = df3[df3['GameKey'].isin(Game_Key_IDs) & df3['PlayID'].isin(Play_IDs) & df3['GSISID'].isin(GSISIDS)]\ndf3_filtered.dropna(subset=['GSISID'], inplace=True) \ndf4_filtered = df4[df4['GameKey'].isin(Game_Key_IDs) & df4['PlayID'].isin(Play_IDs) & df4['GSISID'].isin(GSISIDS)]\ndf4_filtered.dropna(subset=['GSISID'], inplace=True)\ndf5_filtered = df5[df5['GameKey'].isin(Game_Key_IDs) & df5['PlayID'].isin(Play_IDs) & df5['GSISID'].isin(GSISIDS)]\ndf5_filtered.dropna(subset=['GSISID'], inplace=True)\n\ndf1_filtered['GSISID'] = df1_filtered['GSISID'].astype('int64')\ndf2_filtered['GSISID'] = df2_filtered['GSISID'].astype('int64')\ndf3_filtered['GSISID'] = df3_filtered['GSISID'].astype('int64')\ndf4_filtered['GSISID'] = df4_filtered['GSISID'].astype('int64')\ndf5_filtered['GSISID'] = df5_filtered['GSISID'].astype('int64')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"ab87afa4a477a128b966631cb5f71b829d496175"},"cell_type":"code","source":"# 2017 NGS dataframe\nNGS17_data = pd.concat([df1_filtered, df2_filtered, df3_filtered, df4_filtered, df5_filtered])\n# release memory\ndf1 = []\ndf2 = []\ndf3 = []\ndf4 = []\ndf5 = []\n\nNGS_All = pd.concat([NGS16_data,NGS17_data])\n# write to CSV\nNGS_All.to_csv('NGS_All.csv',header=True)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"e4e50f4707cdedf97312300e9003e695e65671a8"},"cell_type":"code","source":"NGS_All.columns = [col.lower() for col in NGS_All.columns]\n# read in concussion plays from video review dataset to build unique key list\nvr = pd.read_csv('../input/NFL-Punt-Analytics-Competition/video_review.csv')\nvr1 = vr[['Season_Year','GameKey','PlayID','GSISID']]\nvr2 = vr[['Season_Year','GameKey','PlayID','Primary_Partner_GSISID']]\nvr2.rename(columns={'Primary_Partner_GSISID': 'GSISID'}, inplace=True)\nvr_final = pd.concat([vr1,vr2])\nvr_final= vr_final.drop_duplicates(['Season_Year','GameKey','PlayID', 'GSISID'])\nunique_grp_ids = vr_final['Season_Year'].astype(str) + vr_final['GameKey'].astype(str) + vr_final['PlayID'].astype(str) + vr_final['GSISID'].astype(str)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"b7625f78ff42c7e555767cfb63593a0d28ee01af"},"cell_type":"code","source":"# Create a Natural Key to use across datasets and in group by statements - sort the dataframe\nNGS_All['groupid'] = NGS_All['season_year'].astype(str) + NGS_All['gamekey'].astype(str) + NGS_All['playid'].astype(str) + NGS_All['gsisid'].astype(str)\nNGS_All = NGS_All.groupby('groupid').apply(lambda x: x.sort_values('time'))\n# remove the multi index created by the above\nNGS_All = NGS_All.reset_index(0, drop=True)\n# filter to only gameids within the video review dataset, record count down to 21604 from 33722\nNGS_All = NGS_All[NGS_All['groupid'].isin(unique_grp_ids)]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"fc4d871f259fde21fdacd3f99fa61579731b2854"},"cell_type":"code","source":"# identify the Start and End of each play according to Event (ball_snap and tackle)\nplay_start = NGS_All.loc[NGS_All['event']=='ball_snap',['time','groupid']]\nplay_start.rename(columns={'time': 'play_start'}, inplace=True)\nplay_end = NGS_All.loc[NGS_All['event']=='tackle',['time','groupid']]\nplay_end.rename(columns={'time': 'play_end'}, inplace=True)\n\nplay_run_times = pd.merge(play_start,play_end,on='groupid',how='inner')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"458deec6308b1ae640dc6efc91b41e07f948c860"},"cell_type":"code","source":"# join NGS_all to play_start and create a play_start column\nNGS_All = pd.merge(NGS_All, play_run_times, on='groupid', how='outer')\n# reduce dataframe to only data after ball is snapped and when the play is blown dead\nngs = NGS_All[(NGS_All['time']>= NGS_All['play_start']) & (NGS_All['time'] <= NGS_All['play_end'])]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"8e87d0752c248c812c799d57abc82e4757a42ada"},"cell_type":"code","source":"# only 45 groupids in the NextGen data that match to video review data out of possible \nngs['groupid'].unique().size","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"81047a8f0d8b7c7562718c7cd8d1446e269e4a38"},"cell_type":"markdown","source":"## Calculate various kinetic properties"},{"metadata":{"trusted":true,"_uuid":"5304631c07887f86ca4f523367301fba52e8ed5c"},"cell_type":"code","source":"# Calculate common attributes like distnace & kinetics - speed, acceleration, instaneous velocity, etc\n\n# create distance in meters, 1 yard = .9144 meters\nngs['distance'] = ngs['dis'] * 0.9144\n# calculate total distance (yards and meters)\nyd_distance_ttl = ngs.groupby(['groupid'])['dis'].sum()\nmt_distance_ttl = ngs.groupby(['groupid'])['distance'].sum()\nyd = yd_distance_ttl.to_frame().reset_index()\nm = mt_distance_ttl.to_frame().reset_index()\n\n# begin creation of a Fact Table\nfact_tbl = pd.merge(yd, m, on='groupid')\nfact_tbl= fact_tbl.rename(columns={'dis': 'yd_ttl', 'distance': 'meter_ttl'})\n\n# to datetime\nngs['time'] = pd.to_datetime(ngs['time'])\n# get total time by play\ntime_diff = ngs.groupby('groupid')['time'].apply(lambda x: x.max() - x.min())\n# change to a dataframe\ntime_diff = time_diff.to_frame().reset_index()\n# merge onto fact table\nfact_tbl = pd.merge(fact_tbl,time_diff, on='groupid')\n# convert into seconds\nfact_tbl['time'] = fact_tbl['time'].dt.seconds\nfact_tbl['avg_speed_m'] = fact_tbl['meter_ttl'] / fact_tbl['time']\nfact_tbl['avg_speed_yd'] = fact_tbl['yd_ttl'] / fact_tbl['time']\n# calc Instantaneous velocity (meters) at every decisecond\nngs['instant_velocity_m'] = ngs['distance'] / .1\nngs = ngs.reset_index(drop=True)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"5daa61868995c241dff2af0e1234b312251332e8"},"cell_type":"code","source":"#store previous velocity\nngs['prev_velocity'] = ngs.groupby(['groupid'])['instant_velocity_m'].shift(1)\n# if first record of group, set initial velocity to 0\nngs['prev_velocity'].fillna(0, inplace=True)\n# calculate instantaneous acceleration\nngs['instant_acceleration'] = ((ngs.instant_velocity_m - ngs.prev_velocity) / .1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"fac8b68481369d18e57c05c0a7757c44d9458472"},"cell_type":"code","source":"# View the comparative speed and distance traveled of the players involved in a concussion\nfact_tbl[fact_tbl['groupid'].str.contains(\"2016144\")]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"64d865c0aff5c94e1494d710f23c2ccf8dfef3c1"},"cell_type":"code","source":"# add additional keys to the fact table\nvr = pd.read_csv('../input/NFL-Punt-Analytics-Competition/video_review.csv')\nvr.columns = [col.lower() for col in vr.columns]\nadditional_keys=vr.drop_duplicates(['gamekey','playid','gsisid','primary_partner_gsisid'])\nak = additional_keys[['season_year','gamekey','playid','gsisid','player_activity_derived','primary_impact_type','primary_partner_gsisid']]\nak2 = additional_keys[['season_year','gamekey','playid','player_activity_derived','primary_impact_type','primary_partner_gsisid']]\nak['groupid'] = additional_keys['season_year'].astype(str) + additional_keys['gamekey'].astype(str) + additional_keys['playid'].astype(str) + additional_keys['gsisid'].astype(str)\nak2['groupid'] = additional_keys['season_year'].astype(str) + additional_keys['gamekey'].astype(str) + additional_keys['playid'].astype(str) + additional_keys['primary_partner_gsisid'].astype(str)\nak2['gsisid'] = ak2['primary_partner_gsisid']","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"52a03ff09aac94230f49b0c55708cd45d725f69e"},"cell_type":"code","source":"#concat full additional keys, clean data\nak3 = pd.concat([ak, ak2])\nak3 = ak3.dropna(axis='rows')\nak3 = ak3[ak3.gsisid != 'Unclear']\nfinal_fact = pd.merge(fact_tbl,ak3,on='groupid')\n# define player type for easier visualization, c=concussed, p=primary partner\nfinal_fact['player_type'] = np.where((final_fact.gsisid == final_fact.primary_partner_gsisid), 'p', 'c')","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"86e121c39bf62850eb034cbd0475cd557d54b71d"},"cell_type":"markdown","source":"# Begin Analyzing and Visualizing the Data"},{"metadata":{"trusted":true,"_uuid":"bdf2a1727cfc659db17cacf7971ccad5736a316c"},"cell_type":"code","source":"import seaborn as sns\nsns.set(color_codes=True)\n\n# split by concussed or primary player impacted\nconcussed = final_fact[final_fact['player_type']=='c'][:]\nprimary = final_fact[final_fact['player_type']=='p'][:]","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"1420d6e7d3e9fb6eecfe5d76ed03a8a19ffb90dd"},"cell_type":"markdown","source":"## Observe Concussed vs Primary Players and Impact Type Distribution"},{"metadata":{"trusted":true,"_uuid":"bd5d6e48a81670971635ce289f8774f460f58dd7"},"cell_type":"code","source":"data = final_fact\nsns.set(style=\"darkgrid\")\ng = sns.catplot(x=\"player_activity_derived\", hue=\"player_type\", col=\"primary_impact_type\",\n                data=data, kind=\"count\");","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"ed9bca8c87158d87d1f106942e014cc2f05ed3a2"},"cell_type":"markdown","source":"## View Avg Distance and Speed for Concussed vs Primary Players"},{"metadata":{"trusted":true,"_uuid":"5e737590b746cb9ea291e34227562ce55047dcee"},"cell_type":"code","source":"# view average distance traveled (yds) & average speed (yds/sec) for concussed and primary partner\n\nf, axes = plt.subplots(1, 2, figsize=(10,5))\nsns.distplot(concussed['yd_ttl'], label=\"Concussed\", kde=False, ax=axes[0])\nsns.distplot(primary['yd_ttl'], label=\"Primary\", kde=False, ax=axes[0])\nsns.distplot(concussed['avg_speed_yd'],label=\"Concussed\", kde=False, ax=axes[1])\nsns.distplot(primary['avg_speed_yd'], label = \"Primary\", kde=False, ax=axes[1])\nplt.legend(loc=(1.04,.5))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"60bc44f68f8f8956df0ac7fada1057e7c7c1a68d"},"cell_type":"code","source":"# look at distribution of speed as a function of distance (yards) for concussed players, where do most instances\n# occur across those variables? \nsns.set(style=\"ticks\")\n\nx = concussed['yd_ttl']\ny = concussed['avg_speed_yd']\nx_primary = primary['yd_ttl']\ny_primary = primary['avg_speed_yd']\n\n\nc = sns.jointplot(x, y, data=concussed, kind=\"scatter\")\np = sns.jointplot(x_primary, y_primary, data=concussed, kind=\"scatter\", color='r')","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"88e9f077d6b90835979cf236f2d46302a1528750"},"cell_type":"markdown","source":"## Most Concussed and Primary Players involved in the concussion are traveling at distances > 40 yds"},{"metadata":{"trusted":true,"_uuid":"26983ca9a30d5ac6902080173a78e5c71faf448b","scrolled":false},"cell_type":"code","source":"# deeper look into the plays where distance traveled is >40yds per the earlier distribution pattern\nviz = final_fact[['groupid','player_type','season_year','gamekey','playid']][final_fact['yd_ttl']>40]\nviz1 = viz.groupby(['season_year','gamekey','playid']).size().reset_index(name='counts')\nviz1 = viz1[viz1['counts']>1]\nviz1 = viz1.reset_index()\n\n# add player type to ngs data to make visualizations simpler\nngs = pd.merge(ngs, final_fact[['player_type','groupid']], on='groupid', how='inner')\n\n# turn into a loop to dynamically draw plots\nimport matplotlib.patches as mpatches\nfor index, row in viz1.iterrows():\n    groupid = row['season_year'].astype(str) + row['gamekey'].astype(str) + row['playid'].astype(str)\n    player_concussed = ngs[ngs['groupid'].str.contains(groupid)] \n    \n    x= []\n    y = []\n    x_primary = []\n    y_primary = []\n        \n    \n    #for every row in player_concussed\n    for i, r in player_concussed.iterrows():\n        \n        if r['player_type']=='c':\n            x.append(r['x'])\n            y.append(r['y'])\n        \n        else:\n            x_primary.append(r['x'])\n            y_primary.append(r['y'])\n    \n    \n    plt.figure(figsize=(6,3))\n    plt.title(\"Year: \" + row['season_year'].astype(str) + \" GameKey: \" + row['gamekey'].astype(str) \n             + \" Play Id: \" + row['playid'].astype(str))\n    plt.scatter(x, y, s=2, c=\"b\");\n    plt.xlabel(\"Field Length (yd)\")\n    plt.ylabel(\"Field Width (yd)\")\n    plt.scatter(x_primary, y_primary, s=2, c=\"r\")\n    blue_patch = mpatches.Patch(color='blue', label='Concussed Player')\n    red_patch = mpatches.Patch(color='red', label='Primary Player')\n    plt.legend(handles=[red_patch,blue_patch])\n    ","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"8d06bb071b8fb05152d63731442b116cebd23977"},"cell_type":"markdown","source":"## Evaluate where players involved in concussions start and end on a play"},{"metadata":{"trusted":true,"_uuid":"e1430888f946de9e5d656ad9e1cfc2526235debc"},"cell_type":"code","source":"# plot starting point for concussed and primary players\nstarting_positions = ngs[(ngs['event']=='ball_snap')]\nstarting_positions = starting_positions[['x','y','groupid']]\nstarting_positions = starting_positions.rename(columns={'x': 'x_start', 'y': 'y_start'})\n# plot ending position for concussed and primary players (not entirely accurate as it is not the exact point of impact\n# where tracking data ends)\nending_positions = ngs[(ngs['event']=='tackle')]\nending_positions = ending_positions[['x','y','groupid']]\nending_positions = ending_positions.rename(columns={'x': 'x_end', 'y': 'y_end'})","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"47238feb7524d854b0c8087b718188e39ada5ff1"},"cell_type":"code","source":"final_fact = pd.merge(final_fact,ending_positions,on='groupid',how='inner')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"15ff1a8d7c2e55d8251c9589007db164d7e4c581"},"cell_type":"code","source":"final_fact = pd.merge(final_fact,starting_positions,on='groupid',how='inner')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"c28addf3680d9c4da085228e411204ad7369be4d"},"cell_type":"code","source":"# calculate distance (yards) traveled height and width-wise of field\nfinal_fact['x_traveled'] = abs(final_fact['x_end'] - final_fact['x_start'])\nfinal_fact['y_traveled'] = abs(final_fact['y_end'] - final_fact['y_start'])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"3661d4c8a9c1e2c396ea879bd804dea698886100"},"cell_type":"code","source":"final_fact.head(5)","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"e57ce5aedd7ffd0258a96bb2fcdb4cc8c900a7d9"},"cell_type":"markdown","source":"## Visualize Location of Concussions"},{"metadata":{"trusted":true,"_uuid":"2e23f4028aa108998568317a11a66804b210bf26"},"cell_type":"code","source":"img = plt.imread(\"../input/football-fieldpng/football_field.png\")\nplt.scatter(final_fact['x_end'], final_fact['y_end'], c=\"r\")\nplt.imshow(img, zorder=0, extent=[0, 100, 0, 53])\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"32d60bce6a4e9b414b51ec6fd871aa059ee99753"},"cell_type":"code","source":"concussed_players = final_fact[final_fact['player_type']=='c']\nsns.jointplot(x=\"x_end\", y=\"y_end\", data=final_fact, kind=\"kde\");","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"f35994b1fffb924ba613b605896c20705df27fa9"},"cell_type":"markdown","source":"### Majority of Concussions occur between the field numerals & directional arrows"},{"metadata":{"trusted":true,"_uuid":"872261bf25be4dc06f81fe8e57dc7acfb3720c65"},"cell_type":"code","source":"# y (width) location on field where concussion occured\nsns.distplot(concussed_players['y_end']);","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"6448885f64b8584458d091c83d4114d0d42f327e"},"cell_type":"markdown","source":"# Only 5/43 concussions occurred at the edges of the field (outside the numbers)"},{"metadata":{"trusted":true,"_uuid":"01c70fe7c5444fa003bdb76b45ffd23c75e09993"},"cell_type":"code","source":"len(concussed_players[concussed_players['y_end'].between(43, 53, inclusive=True)]) + len(concussed_players[concussed_players['y_end'].between(0, 10, inclusive=True)])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"81169c44a51cd579c64fa51e849103c1c0ece91e"},"cell_type":"code","source":"## Observe all NFL Punt Plays\npunts = pd.read_csv('../input/NFL-Punt-Analytics-Competition/play_information.csv')\npunts.columns = [col.lower() for col in punts.columns]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"a64ff1eeba425c1ecdaa15ac3fc51fb118d32ace"},"cell_type":"code","source":"# create a key\npunts['key'] = punts['season_year'].astype(str) + punts['gamekey'].astype(str) + punts['playid'].astype(str)\n# modify description to be a string for parsing\npunts['playdescription'] = punts['playdescription'].astype(str)\n\n# search for fair catch punts\nimport re\nfair_catch = []\nfor row in punts['playdescription']:\n    match = re.search('fair catch', row)\n    if match:\n        fair_catch.append(1)\n    elif match is None:\n        fair_catch.append(0)\n        \npunts[\"fair_catch\"] = fair_catch   \n\n#create lists for concussion play keys\ngamekeys = concussed_players['gamekey']\nplayids = concussed_players['playid']\npunts2 = punts[punts['fair_catch']==1]\n\nfair_catch_concussed = punts2[punts2['gamekey'].isin(gamekeys) & punts2['playid'].isin(playids)]\n# Only 1 fair catch resulted in a concussion","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"947bb877e9511ce9a4bfc6ad0d6bcaa39aa369d3"},"cell_type":"code","source":"# .53% of all punnt plays result in concussions\n((vr.gamekey.count() -1 )/ punts.gamekey.count() * 100)\n","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"339983c500c4126283250bd867a9eabe681bbcec"},"cell_type":"markdown","source":"**6,681** total punt plays<br>\n**1,659** fair catches, **5,021** not fair caught<br>\n**1** fair catch resulted in concussion<br>\n**36** concussions from punts (1 punt was a fake)<br><br>\n\nOnly __24%__ of punts are fair caught. Of those, only **1 (.06%)** has ever resulted in a concussion as oppposed to the **37 (.72%)** punts that were chosen to be returned AND resulted in a concussion injury."},{"metadata":{"trusted":true,"_uuid":"9e641e8277b8b64b445b5a4526d212e7ed2873d5"},"cell_type":"code","source":"#Rule proposals have been submitted via the assosciated presentation.","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"4c0b10659b2473774900fd4eabeab4900305c7b1"},"cell_type":"code","source":"","execution_count":null,"outputs":[]}],"metadata":{"kernelspec":{"display_name":"Python 3","language":"python","name":"python3"},"language_info":{"codemirror_mode":{"name":"ipython","version":3},"file_extension":".py","mimetype":"text/x-python","name":"python","nbconvert_exporter":"python","pygments_lexer":"ipython3","version":"3.7.1"}},"nbformat":4,"nbformat_minor":1}