{"cells":[{"metadata":{},"cell_type":"markdown","source":"# NFL 1st and Future - Analytics\n<img src=\"https://cdnph.upi.com/svc/sv/upi/1071539395166/2018/1/2c5514a422dde6ac1c1d69df891ac3af/Fantasy-Football-Whos-In-Whos-Out-Week-6-NFL-injury-report.jpg\" alt=\"W3Schools.com\">\nsrc=https://cdnph.upi.com/svc/sv/upi/1071539395166/2018/1/2c5514a422dde6ac1c1d69df891ac3af/Fantasy-Football-Whos-In-Whos-Out-Week-6-NFL-injury-report.jpg"},{"metadata":{},"cell_type":"markdown","source":"##### In this challenge, our  tasked to investigate the relationship between the playing surface and the injury and performance of National Football League (NFL) athletes and to examine factors that may contribute to lower extremity injuries.Challenge is to characterize any differences in player movement between the playing surfaces and to identify specific variables (e.g., field surface, weather, position, play type, etc.) that may influence player movement and the risk of injury."},{"metadata":{},"cell_type":"markdown","source":"# Describe Data\nThere are three files provided in the dataset, as described below:\n\nInjury Record: The injury record file in .csv format contains information on 105 lower-limb injuries that occurred during regular season games over the two seasons. Injuries can be linked to specific records in a player history using the PlayerKey, GameID, and PlayKey fields.\n\nPlay List: – The play list file contains the details for the 267,005 player-plays that make up the dataset. Each play is indexed by PlayerKey, GameID, and PlayKey fields. Details about the game and play include the player’s assigned roster position, stadium type, field type, weather, play type, position for the play, and position group.\n\nPlayer Track Data: player level data that describes the location, orientation, speed, and direction of each player during a play recorded at 10 Hz (i.e. 10 observations recorded per second)."},{"metadata":{},"cell_type":"markdown","source":"\n# Analysis\n#### This report represent my analysis of injury happened in matches.It is my opinion that based on given data and my analysis.\nIMPORTANT ANALYSIS: \n* On synthetic surface player has probelm to change his orientation.This decrease the agility of player.\n* The player movement is major cause of injury happened :\n  * If player move with constant speed for some time and he is changing  his orientation more frequently while running,then he will more likely to get injured.\n  * If player run with dynamic speed and his orientation is constant then it will more like to get injured.\n\n# Some more result :\n* Stadium Type is major cause of injury.If player played in outdoor stadium then their probability of getting injury is very high.It depend on temperature and Weather also.\n* PlayType has also important to distinguish injury play.The playtype Pass and Rush has more injury.\n* More injury happened at Knee and ANKLE bodypart because of player move at high speed.\n* If Knee injury happened then it high probability that it may stay for more than 7 days.\n* Most injury happened at start of match.\n* Cloudly and low temperature will related to injury.\n\nIn this notebook we will  prove this analysis.<br>\n\n\nLET's GO________________________________________\n\n"},{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true,"_kg_hide-input":true,"_kg_hide-output":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 scipy.stats as st\n\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":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"injury_data=pd.read_csv('../input/nfl-playing-surface-analytics/InjuryRecord.csv')\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"playertrackdata=pd.read_csv(\"../input/nfl-playing-surface-analytics/PlayerTrackData.csv\")\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"playlist=pd.read_csv('../input/nfl-playing-surface-analytics/PlayList.csv')\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"\ninjury_data.groupby('Surface').count()['PlayerKey'].sort_values().plot(kind='bar',title='Number of Unique surface')\nprint(\"Probability of Injury happened at Natural Surface = \",str((len(injury_data[injury_data['Surface']=='Natural']['PlayerKey'].values)/injury_data.shape[0])*100))\nprint(\"Probability of Injury happened at Synthetic Surface = \",str((len(injury_data[injury_data['Surface']=='Synthetic']['PlayerKey'].values)/injury_data.shape[0])*100))","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"<h3> Synthetic has more injury than natural."},{"metadata":{"trusted":true},"cell_type":"code","source":"injured_play1=playertrackdata[playertrackdata['PlayKey']=='46587-2-13']\ninjured_play2=playertrackdata[playertrackdata['PlayKey']=='46119-3-16']\ninjured_play3=playertrackdata[playertrackdata['PlayKey']=='38364-5-23']\ninjured_play4=playertrackdata[playertrackdata['PlayKey']=='35611-7-42']\nnoninjured_play1=playertrackdata[playertrackdata['PlayKey']=='35611-4-36']\nnoninjured_play2=playertrackdata[playertrackdata['PlayKey']=='44434-9-31']\nnoninjured_play3=playertrackdata[playertrackdata['PlayKey']=='45966-3-29']\nnoninjured_play4=playertrackdata[playertrackdata['PlayKey']=='30068-6-55']\nnoninjured_play5=playertrackdata[playertrackdata['PlayKey']=='46832-2-8']","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(\"injured play playtype 1 = \",playlist[playlist['PlayKey']=='46587-2-13']['PlayType'].values[0])\nprint(\"injured play FieldType 1 = \",playlist[playlist['PlayKey']=='46587-2-13']['FieldType'].values[0])\nprint(\" injured play playtype 2 = \",playlist[playlist['PlayKey']=='38364-5-23']['PlayType'].values[0])\nprint(\"injured play FieldType 2 = \",playlist[playlist['PlayKey']=='38364-5-23']['FieldType'].values[0])\nprint(\"NonInjured play playtype 1 = \",playlist[playlist['PlayKey']=='38228-3-8']['PlayType'].values[0])\nprint(\"NonInjured play Fieldtype 1 = \",playlist[playlist['PlayKey']=='38228-3-8']['FieldType'].values[0])\nprint(\"NonInjured play playtype 2 = \",playlist[playlist['PlayKey']=='46832-2-8']['PlayType'].values[0])\nprint(\"NonInjured play Fieldtype 2 = \",playlist[playlist['PlayKey']=='46832-2-8']['FieldType'].values[0])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"fig, axes = plt.subplots(nrows=1, ncols=2, figsize=(24,10))\n\naxes.flatten()[0].set_title(\"INJURED PLAY SPEED\")\naxes.flatten()[1].set_title(\"NONINJURED PLAY SPEED\")\nsns.kdeplot(injured_play1['s'], ax=axes.flatten()[0],label=\"Injured Play1\")\n\nsns.kdeplot(injured_play3['s'], ax=axes.flatten()[0],label=\"Injured Play2\")\nsns.kdeplot(noninjured_play5['s'],ax=axes.flatten()[1],label=\"NON Injured Play1\")\n\nsns.kdeplot(noninjured_play4['s'],ax=axes.flatten()[1],label=\"NON Injured Play2\")","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"You can see that injuryplay1 has constant speed and also have high speed and injuryplay2 not moving at constant speed,because it has wide spread of distribution and from non injury play that both play with slightly constant speed but not as high as injuryplay.<br>\n\nInjuryplay1 has very wide spread at one sided and having high probability around speed 0.1 this shows player having constant speed and changes his speed very fast as it become very stipped at one side or we can say it drop very fast at one sided of distribution.It also have some probability around 0.8 to 1.This show player play at high speed also.<br>\n\nInjuryplay2 does not changes his speed suddenly and also having wide spread of distribution this show that is also running on high speed but not for long time as it does not having high probability like injuryplay1.It has some more probability around 0.6 to 0.8 speed than injuryplay1.<br>\n\nThis analysis is done on synthetic surface and we see that there are  two different type of distribution from injury play."},{"metadata":{"trusted":true},"cell_type":"code","source":"fig, axes = plt.subplots(nrows=1, ncols=2, figsize=(24,10))\n\naxes.flatten()[0].set_title(\"INJURED PLAY Distance\")\naxes.flatten()[1].set_title(\"NONINJURED PLAY Distance\")\nsns.kdeplot(injured_play1['dis'], ax=axes.flatten()[0],label=\"Injured Play1\")\n\nsns.kdeplot(injured_play3['dis'], ax=axes.flatten()[0],label=\"Injured Play2\")\n\nsns.kdeplot(noninjured_play5['dis'],ax=axes.flatten()[1],label=\"NON Injured Play1\")\n\nsns.kdeplot(noninjured_play4['dis'],ax=axes.flatten()[1],label=\"NON Injured Play2\")","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"This distribution is similar to speed distribution and we can analysis that speed is related to distance also.\n"},{"metadata":{"trusted":true},"cell_type":"code","source":"fig, axes = plt.subplots(nrows=1, ncols=2, figsize=(15,5))\n\naxes.flatten()[0].set_title(\"INJURED PLAY Orientation\")\naxes.flatten()[1].set_title(\"NONINJURED PLAY Orientation\")\nsns.kdeplot(injured_play1['o'], ax=axes.flatten()[0],label=\"Injured Play1\")\n\nsns.kdeplot(injured_play3['o'], ax=axes.flatten()[0],label=\"Injured Play2\")\nsns.kdeplot(noninjured_play5['o'],ax=axes.flatten()[1],label=\"NON Injured Play1\")\n\nsns.kdeplot(noninjured_play4['o'],ax=axes.flatten()[1],label=\"NON Injured Play2\")","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"From injuryplay1 distribution ,distribution is widely spread has more probability around 300 and 0 angle.This show that player changing his orientation anticlockwise and clockwise both frequently.This show that player play with dynamic orientation.From previous analysis of speed distribution of injuryplay1 there player play with constant speed for long time.\n\nFrom injuryplay2 distribution ,distribution is high probability around 100 angle,this show that player play more likely around 100 angle and not changing his angle dastrically as we see two peak and 150 angle also,so he also not changing his orientation around 150 angle.This player not changing is orientation more frequently.\nFrom injuryplay2 speed distribution previous analysis the player play with more dynamics speed and also run at high speed also.\n\nFrom both noninjury play you opposite type of analysis we get from here.\n\nYou can intuitly think that , if player play at high speed and dynamically changing his orientation this will lead to more injury.and if player play with dynamic speed and not changing his orientation frequently then this lead to tackle by other player and getting injured."},{"metadata":{"trusted":true},"cell_type":"code","source":"fig, axes = plt.subplots(nrows=1, ncols=2, figsize=(24,10))\n\naxes.flatten()[0].set_title(\"INJURED PLAY Direction\")\naxes.flatten()[1].set_title(\"NONINJURED PLAY Direction\")\nsns.kdeplot(injured_play1['dir'], ax=axes.flatten()[0],label=\"Injured Play1\")\n\nsns.kdeplot(injured_play3['dir'], ax=axes.flatten()[0],label=\"Injured Play2\")\nsns.kdeplot(noninjured_play5['dir'],ax=axes.flatten()[1],label=\"NON Injured Play1\")\n\nsns.kdeplot(noninjured_play4['dir'],ax=axes.flatten()[1],label=\"NON Injured Play2\")","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"From injuryplay1 same type of distribution what we say at orientation distibution.\nFrom injuryplay2 similiar type of distibution but this shows that he also changing is direction."},{"metadata":{},"cell_type":"markdown","source":"### We are taking different playtype and different surface and find relation with previous outcome."},{"metadata":{"trusted":true},"cell_type":"code","source":"print(\"injured play playtype 1 = \",playlist[playlist['PlayKey']=='44421-12-41']['PlayType'].values[0])\nprint(\"injured play FieldType 1 = \",playlist[playlist['PlayKey']=='44421-12-41']['FieldType'].values[0])\nprint(\" injured play playtype 2 = \",playlist[playlist['PlayKey']=='41094-1-55']['PlayType'].values[0])\nprint(\"injured play FieldType 2 = \",playlist[playlist['PlayKey']=='41094-1-55']['FieldType'].values[0])\nprint(\"NonInjured play playtype 1 = \",playlist[playlist['PlayKey']=='26624-5-5']['PlayType'].values[0])\nprint(\"NonInjured play Fieldtype 1 = \",playlist[playlist['PlayKey']=='26624-5-5']['FieldType'].values[0])\nprint(\"NonInjured play playtype 2 = \",playlist[playlist['PlayKey']=='47888-11-55']['PlayType'].values[0])\nprint(\"NonInjured play Fieldtype 2 = \",playlist[playlist['PlayKey']=='47888-11-55']['FieldType'].values[0])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"injured_play1=playertrackdata[playertrackdata['PlayKey']=='44421-12-41']\ninjured_play2=playertrackdata[playertrackdata['PlayKey']=='41094-1-55']\n\nnoninjured_play1=playertrackdata[playertrackdata['PlayKey']=='26624-5-5']\nnoninjured_play2=playertrackdata[playertrackdata['PlayKey']=='47888-11-55']\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"fig, axes = plt.subplots(nrows=1, ncols=2, figsize=(24,10))\n\naxes.flatten()[0].set_title(\"INJURED PLAY Distance\")\naxes.flatten()[1].set_title(\"NONINJURED PLAY Distance\")\nsns.kdeplot(injured_play1['dis'], ax=axes.flatten()[0],label=\"Injured Play1\")\n\nsns.kdeplot(injured_play2['dis'], ax=axes.flatten()[0],label=\"Injured Play2\")\nsns.kdeplot(noninjured_play1['dis'],ax=axes.flatten()[1],label=\"NON Injured Play1\")\n\nsns.kdeplot(noninjured_play2['dis'],ax=axes.flatten()[1],label=\"NON Injured Play2\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"fig, axes = plt.subplots(nrows=1, ncols=2, figsize=(24,10))\n\naxes.flatten()[0].set_title(\"INJURED PLAY SPEED\")\naxes.flatten()[1].set_title(\"NONINJURED PLAY SPEED\")\nsns.kdeplot(injured_play1['s'], ax=axes.flatten()[0],label=\"Injured Play1\")\n\nsns.kdeplot(injured_play2['s'], ax=axes.flatten()[0],label=\"Injured Play2\")\nsns.kdeplot(noninjured_play1['s'],ax=axes.flatten()[1],label=\"NON Injured Play1\")\n\nsns.kdeplot(noninjured_play2['s'],ax=axes.flatten()[1],label=\"NON Injured Play2\")","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"From speed distribution of injuryplay1 the player play with dynamic speed and more likely having 0.2 or 0.3 speed as it has high peak around that.<br>\nFrom speed distribtution of injuryplay2 the player has high peak at around 0.1 or 0.2 this shows that player play with constant speed for long time.It is also having peak at 6 this show that it also run on high speed.<br>\nThese type of distibution we saw it earlier which is more similary to this one.<br>\nWe are taking different type of play and different surface also and we saw similar distribution also.These show that natural and synthetic having similarity in speed also.<br>"},{"metadata":{"trusted":true},"cell_type":"code","source":"fig, axes = plt.subplots(nrows=1, ncols=2, figsize=(15,5))\n\naxes.flatten()[0].set_title(\"INJURED PLAY Orientation\")\naxes.flatten()[1].set_title(\"NONINJURED PLAY Orientation\")\nsns.kdeplot(injured_play1['o'], ax=axes.flatten()[0],label=\"Injured Play1\")\n\nsns.kdeplot(injured_play2['o'], ax=axes.flatten()[0],label=\"Injured Play2\")\nsns.kdeplot(noninjured_play1['o'],ax=axes.flatten()[1],label=\"NON Injured Play1\")\n\nsns.kdeplot(noninjured_play2['o'],ax=axes.flatten()[1],label=\"NON Injured Play2\")","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"From injuryplay1 orientation distribution it has high probability around 250 to 350 and also around 100 this show that player play with dynamic orientation.Player more likely to change his orientation at clockwise direction.\nFrom injuryplay2 orienation ditribution it has high peak around 0 and 300 t0 360 also these shows that player are not changing his orientation more likely.His orientation will change anticlockwise or clockwise also.\n\nWe find similar result from these which we got earlier also. <br>\nBut we haven't saw orientation distibution similar to previous distribution these shows that orientation is somehow different for synthetic surface.\n"},{"metadata":{},"cell_type":"markdown","source":"<h3> <p style=\"color:MediumSeaGreen;\">  Summary :<br>\n   Thus we analysis that player speed and orientation is related to there injury but orientation is related to surface also:<br>\n    What we got from this analysis<br>\n  1. If player play with constant speed for long time and thier orientation changes dynamically then it will more likely to get injured.<br>\n  2. If player play with dynamic speed and their orientation doesnot changes frequently then he will more likely to get injured.\n    \n    \n    \n    \n</p>"},{"metadata":{},"cell_type":"markdown","source":"# Analysis of Orientation"},{"metadata":{"trusted":true},"cell_type":"code","source":"injury_data=injury_data.dropna()\nnatural_surface=injury_data[injury_data['Surface']=='Natural']['PlayKey']\nsynthetic_surface=injury_data[injury_data['Surface']=='Synthetic']['PlayKey']\nonnatural_surface_speed=[]\nonnatural_surface_distance=[]\nonnatural_surface_orientation=[]\nonnatural_surface_direction=[]\nfor key in natural_surface:\n    playkey=playertrackdata[playertrackdata['PlayKey']==key]\n    onnatural_surface_speed.extend(playkey['s'])\n    onnatural_surface_distance.extend(playkey['dis'])\n    onnatural_surface_orientation.extend(playkey['o'])\n    onnatural_surface_direction.extend(playkey['dir'])\nonsynthetic_surface_speed=[]\nonsynthetic_surface_distance=[]\nonsynthetic_surface_orientation=[]\nonsynthetic_surface_direction=[]\nfor key in synthetic_surface:\n    playkey=playertrackdata[playertrackdata['PlayKey']==key]\n    onsynthetic_surface_speed.extend(playkey['s'])\n    onsynthetic_surface_distance.extend(playkey['dis'])\n    onsynthetic_surface_orientation.extend(playkey['o'])\n    onsynthetic_surface_direction.extend(playkey['dir'])\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"noninj_natural_surface=playlist[playlist['FieldType']=='Natural']['PlayKey']\nnoninj_synthetic_surface=playlist[playlist['FieldType']=='Synthetic']['PlayKey']\nnon_inj_natural_surface=np.random.choice(noninj_natural_surface,30,replace=False)\nnon_inj_synthetic_surface=np.random.choice(noninj_synthetic_surface,30,replace=False)\nnoninj_onnatural_surface_speed=[]\nnoninj_onnatural_surface_distance=[]\nnoninj_onnatural_surface_orientation=[]\nnoninj_onnatural_surface_direction=[]\nfor key in non_inj_natural_surface:\n    playkey=playertrackdata[playertrackdata['PlayKey']==key]\n    noninj_onnatural_surface_speed.extend(playkey['s'])\n    noninj_onnatural_surface_distance.extend(playkey['dis'])\n    noninj_onnatural_surface_orientation.extend(playkey['o'])\n    noninj_onnatural_surface_direction.extend(playkey['dir'])\nnoninj_onsynthetic_surface_speed=[]\nnoninj_onsynthetic_surface_distance=[]\nnoninj_onsynthetic_surface_orientation=[]\nnoninj_onsynthetic_surface_direction=[]\nfor key in non_inj_synthetic_surface:\n    playkey=playertrackdata[playertrackdata['PlayKey']==key]\n    noninj_onsynthetic_surface_speed.extend(playkey['s'])\n    noninj_onsynthetic_surface_distance.extend(playkey['dis'])\n    noninj_onsynthetic_surface_orientation.extend(playkey['o'])\n    noninj_onsynthetic_surface_direction.extend(playkey['dir'])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"sns.kdeplot(onnatural_surface_speed,label='Natural')\nsns.kdeplot(onsynthetic_surface_speed,label='Synthetic')\nplt.vlines(np.mean(onnatural_surface_speed),ymin=0,ymax=0.3,label='Natural Mean {}'.format(np.mean(onnatural_surface_speed)),color='b')\nplt.vlines(np.median(onnatural_surface_speed),ymin=0,ymax=0.3,label='Natural Median {}'.format(np.median(onnatural_surface_speed)),linestyles='dotted',color='b')\nplt.vlines(np.mean(onsynthetic_surface_speed),ymin=0,ymax=0.8,label='Synthetic Mean {}'.format(np.mean(onsynthetic_surface_speed)),color='k')\nplt.vlines(np.median(onsynthetic_surface_speed),ymin=0,ymax=0.8,label='Synthetic Median {}'.format(np.median(onsynthetic_surface_speed)),linestyles='dotted',color='k')\nplt.legend()\nplt.title(\"SPEED OF INJURED PLAYER\")","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"<h2><i>More injury happened at high speed on natural surface and at slow speed on synthetic surface also has injury.\n"},{"metadata":{"trusted":true},"cell_type":"code","source":"sns.kdeplot(onnatural_surface_speed,label='Injured')\nsns.kdeplot(noninj_onnatural_surface_speed,label='Not Injured')\nplt.vlines(np.mean(onnatural_surface_speed),ymin=0,ymax=0.3,label='Injured Mean {}'.format(np.mean(onnatural_surface_speed)),color='b')\nplt.vlines(np.median(onnatural_surface_speed),ymin=0,ymax=0.3,label='Injured Median {}'.format(np.median(onnatural_surface_speed)),linestyles='dotted',color='b')\nplt.vlines(np.mean(noninj_onnatural_surface_speed),ymin=0,ymax=0.8,label='NotInjured Mean {}'.format(np.mean(noninj_onnatural_surface_speed)),color='k')\nplt.vlines(np.median(noninj_onnatural_surface_speed),ymin=0,ymax=0.8,label='NotInjured Median {}'.format(np.median(noninj_onnatural_surface_speed)),linestyles='dotted',color='k')\nplt.legend()\nplt.title(\"Speed on natural surface\")","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"<i> Both speed on injured and notinjured play has similar speed that show injury doesnot  related to  natural surface."},{"metadata":{"trusted":true},"cell_type":"code","source":"\nsns.kdeplot(noninj_onsynthetic_surface_speed,label='NotInjured')\nsns.kdeplot(onsynthetic_surface_speed,label='Injured')\nplt.vlines(np.mean(noninj_onsynthetic_surface_speed),ymin=0,ymax=0.3,label='NotInjured Mean {}'.format(np.mean(noninj_onsynthetic_surface_speed)),color='b')\nplt.vlines(np.median(noninj_onsynthetic_surface_speed),ymin=0,ymax=0.3,label='NotInjured Median {}'.format(np.median(noninj_onsynthetic_surface_speed)),linestyles='dotted',color='b')\nplt.vlines(np.mean(onsynthetic_surface_speed),ymin=0,ymax=0.8,label='Injured Mean {}'.format(np.mean(onsynthetic_surface_speed)),color='k')\nplt.vlines(np.median(onsynthetic_surface_speed),ymin=0,ymax=0.8,label='Injured Median {}'.format(np.median(onsynthetic_surface_speed)),linestyles='dotted',color='k')\nplt.legend()\nplt.title(\"Speed on synthetic surface\")","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"<i> On synthetic surface injuryplay has slow speed then notinjured play still it get injury at mean there is some other variable which is related to injury happening at slow speed on synthetic surface\n"},{"metadata":{"trusted":true},"cell_type":"code","source":"def change(list1):\n    change_list1=[]\n    for index in range(1,len(list1)):\n        change_list1.append(list1[index]-list1[index-1])\n    return change_list1","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.figure(figsize=(20,10))\nsns.kdeplot(onnatural_surface_orientation,label='Injured')\nsns.kdeplot(noninj_onnatural_surface_orientation,label='Not Injured')\nplt.vlines(np.mean(onnatural_surface_orientation),ymin=0,ymax=0.003,label='Injured Mean {}'.format(np.mean(onnatural_surface_orientation)),color='b')\nplt.vlines(np.median(onnatural_surface_orientation),ymin=0,ymax=0.003,label='Injured Median {}'.format(np.median(onnatural_surface_orientation)),linestyles='dotted',color='b')\nplt.vlines(np.mean(noninj_onnatural_surface_orientation),ymin=0,ymax=0.003,label='NotInjured Mean {}'.format(np.mean(noninj_onnatural_surface_orientation)),color='k')\nplt.vlines(np.median(noninj_onnatural_surface_orientation),ymin=0,ymax=0.003,label='NotInjured Median {}'.format(np.median(noninj_onnatural_surface_orientation)),linestyles='dotted',color='k')\n\nplt.legend(loc=2)\nplt.title(\"orientation on natural surface\")","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"<i>From injury distribution,we see that there is peak at arounf 200 angle and after that it has high probability.You can see that from 200 to 350 angle there are high probability as it's distribution has more peak in this region and from 0 to 200 there distribution is down from other distribution this show that player more likely to move around 200 to 350 angle or we can say player move clockwise direction more.<br>\n<i>From noninjury distribution,we see that there is equal distribution and less probability around 200 angle."},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.figure(figsize=(20,10))\nsns.kdeplot(noninj_onsynthetic_surface_orientation,label='NotInjured')\nsns.kdeplot(onsynthetic_surface_orientation,label='Injured')\nplt.vlines(np.mean(noninj_onsynthetic_surface_orientation),ymin=0,ymax=0.003,label='NotInjured Mean {}'.format(np.mean(noninj_onsynthetic_surface_orientation)),color='b')\nplt.vlines(np.median(noninj_onsynthetic_surface_orientation),ymin=0,ymax=0.003,label='NotInjured Median {}'.format(np.median(noninj_onsynthetic_surface_orientation)),linestyles='dotted',color='b')\nplt.vlines(np.mean(onsynthetic_surface_orientation),ymin=0,ymax=0.003,label='Injured Mean {}'.format(np.mean(onsynthetic_surface_orientation)),color='k')\nplt.vlines(np.median(onsynthetic_surface_orientation),ymin=0,ymax=0.003,label='Injured Median {}'.format(np.median(onsynthetic_surface_orientation)),linestyles='dotted',color='k')\n\nplt.legend(loc=2)\nplt.title(\"orientation on synthetic surface\")","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"<i>From injury distribution we saw that around 0 to 200 angle there is high probability other than any angle.These show that player play more likely at 0 to 200 angle.<br>\n<i>From notinjury distribution we saw a peak at around 300 angle this show that player has more likely to found around 300 angle."},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.figure(figsize=(20,10))\nsns.kdeplot(change(onnatural_surface_orientation),label='Injured')\nsns.kdeplot(change(noninj_onnatural_surface_orientation),label='noninjured')\nplt.vlines(np.mean(change(onnatural_surface_orientation)),ymin=0,ymax=0.03,label='Injured Mean {}'.format(np.mean(change(onnatural_surface_orientation))),color='b')\nplt.vlines(np.median(change(onnatural_surface_orientation)),ymin=0,ymax=0.03,label='Injured Median {}'.format(np.median(change(onnatural_surface_orientation))),linestyles='dotted',color='b')\nplt.vlines(np.mean(change(noninj_onnatural_surface_orientation)),ymin=0,ymax=0.03,label='Notinjured Mean {}'.format(np.mean(change(noninj_onnatural_surface_orientation))),color='b')\nplt.vlines(np.median(change(noninj_onnatural_surface_orientation)),ymin=0,ymax=0.03,label='Notinjured Median {}'.format(np.median(change(noninj_onnatural_surface_orientation))),linestyles='dotted',color='b')\n\nplt.legend(loc=2)\nplt.title(\"Orientation on Natural surface\")","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"<i>As we see that injured mean is negative and from previous orientation analysis we find that on natural surface angle is between 200 - 360 is more probably so we say that if played more often change is orientation in clockwise direction he will more likely to get injured.As our orientation is give in clockwise direction.\n<i>Most of injury happened at high speed on natural surface.so changing orientation is difficult at high speed.And from notinjured play there mean and median is more centered."},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.figure(figsize=(20,10))\nsns.kdeplot(change(onsynthetic_surface_orientation),label='INJURED')\nplt.vlines(np.mean(change(onsynthetic_surface_orientation)),ymin=0,ymax=0.03,label='INJURED Mean {}'.format(np.mean(change(onsynthetic_surface_orientation))),color='b')\nplt.vlines(np.median(change(onsynthetic_surface_orientation)),ymin=0,ymax=0.03,label='INJURED Median {}'.format(np.median(change(onsynthetic_surface_orientation))),linestyles='dotted',color='b')\nsns.kdeplot(change(noninj_onsynthetic_surface_orientation),label='NOTINJURED')\nplt.vlines(np.mean(change(noninj_onsynthetic_surface_orientation)),ymin=0,ymax=0.03,label='NOTINJURED Mean {}'.format(np.mean(change(noninj_onsynthetic_surface_orientation))),color='b')\nplt.vlines(np.median(change(noninj_onsynthetic_surface_orientation)),ymin=0,ymax=0.03,label='NOTINJURED Median {}'.format(np.median(change(noninj_onsynthetic_surface_orientation))),linestyles='dotted',color='b')\nplt.legend(loc=2)\nplt.title(\"Orientation on synthetic surface\")","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"* <i>From this,our mean is negative for injury play and from previous analysis we find that on synthetic surface injuryplay more likely have 0 to 200 angle this show that player most move in anticlock wise direction.And from natural surface analysis we can predict that there is some movement lose on synthetic surface this show  that on synthetic surface player more likely not changes his orientation or we can say that it hard to change orientation on synthetic surface"},{"metadata":{},"cell_type":"markdown","source":"<h1>Thus from this analysis we found that on synthetic surface player movement is restricted."},{"metadata":{},"cell_type":"markdown","source":"# OTHER ANALYSIS"},{"metadata":{"trusted":true,"_kg_hide-input":true,"_kg_hide-output":true},"cell_type":"code","source":"\ninjury_data.groupby('BodyPart').count()['PlayerKey'].sort_values().plot(kind='bar',title='Number of Unique  injured BodyPart ')","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Bodypart: Knee and Ankle are mostly affected when injury happen. "},{"metadata":{},"cell_type":"markdown","source":"# Multi-Variate Analysis"},{"metadata":{"trusted":true},"cell_type":"code","source":"print(injury_data.groupby(['Surface','BodyPart']).count()['PlayerKey'].unstack('BodyPart'))\ninjury_data.groupby(['BodyPart','Surface']) \\\n    .count().unstack('BodyPart')['PlayerKey'].T.sort_values('Natural').T \\\n    .sort_values('Ankle') \\\n    .plot(kind='bar', title='Injury Body Part by Turf Type')\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def count_probability(bodypart,surface):\n    bodypart_surface=(injury_data['BodyPart']==bodypart) & (injury_data['Surface']==surface)\n    total_particular_surface=injury_data[injury_data['Surface']==surface]['PlayerKey'].count()\n    prob=bodypart_surface.sum()/total_particular_surface\n    return round(prob,4)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(\"Probability of Ankle injury happened by Natural surface = \"+str(count_probability('Ankle',\"Natural\")))\nprint(\"Probability of Ankle injury happened by Synthetic surface = \"+str(count_probability('Ankle',\"Synthetic\")))\nprint(\"---------------------\")\nprint(\"Probability of Knee injury happened by Natural surface = \"+str(count_probability('Knee',\"Natural\")))\nprint(\"Probability of Knee injury happened by Synthetic surface = \"+str(count_probability('Knee',\"Synthetic\")))\nprint(\"---------------------\")\nprint(\"Probability of Heel injury happened by Natural surface = \"+str(count_probability('Heel',\"Natural\")))\nprint(\"Probability of Heel injury happened by Synthetic surface = 0\")\nprint(\"---------------------\")\nprint(\"Probability of Toes injury happened by Natural surface = \"+str(count_probability('Toes',\"Natural\")))\nprint(\"Probability of Toes injury happened by Synthetic surface = \"+str(count_probability('Toes',\"Synthetic\")))\nprint(\"---------------------\")\nprint(\"Probability of Foot injury happened by Natural surface = \"+str(count_probability('Foot',\"Natural\")))\nprint(\"Probability of Foot injury happened by Synthetic surface = \"+str(count_probability('Foot',\"Synthetic\")))\nprint(\"---------------------\")\n","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"On natural surface bodypart knee has more injury rate and on synthetic surface ankle bodypart is more affected.Heel injury happen only on natural surface but only one injury is notice so we can't analysis from that."},{"metadata":{"trusted":true},"cell_type":"code","source":"injury_data['DM_M_Total']=injury_data['DM_M1']+injury_data['DM_M7']+injury_data['DM_M28']+injury_data['DM_M42']\nprint(injury_data.groupby(['DM_M_Total','Surface']).count().unstack('DM_M_Total')['PlayerKey'])\ninjury_data.groupby(['DM_M_Total','Surface']) \\\n    .count().unstack('DM_M_Total')['PlayerKey'].T.sort_values('DM_M_Total').T.sort_values('Surface').plot(kind='bar',title='Injury happened for days by surface')","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Here<br>\n1 means More than 1 day player get injured.<br>\n2 mean more than 7 days player get injured.<br>\n3 means more than 28 days player get injured.<br>\n4 means more than 42 days player get injured.<br>\n\nThere is equal probability that if player get injured for more that 1 days then it will more likey to stay for more or less than 42 days.\n\n"},{"metadata":{"trusted":true},"cell_type":"code","source":"def count_probability(total_injured_dates,surface):\n    both_happened=(injury_data['DM_M_Total']==total_injured_dates) & (injury_data['Surface']==surface)\n    total_particular_surface=injury_data[injury_data['Surface']==surface]['PlayerKey'].count()\n    prob=both_happened.sum()/total_particular_surface\n    return round(prob,4)\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(\"Probability of having injury more than 1 days due to natural surface = \"+str(count_probability(1,'Natural')))\nprint(\"Probability of having injury more than 1 days due to synthetic surface = \"+str(count_probability(1,'Synthetic')))\nprint(\"--------------------------\")\nprint(\"Probability of having injury more than 7 days due to natural surface = \"+str(count_probability(2,'Natural')))\nprint(\"Probability of having injury more than 7 days due to synthetic surface = \"+str(count_probability(2,'Synthetic')))\nprint(\"--------------------------\")\nprint(\"Probability of having injury more than 28 days due to natural surface = \"+str(count_probability(3,'Natural')))\nprint(\"Probability of having injury more than 28 days due to synthetic surface = \"+str(count_probability(3,'Synthetic')))\nprint(\"--------------------------\")\nprint(\"Probability of having injury more than 42 days due to natural surface = \"+str(count_probability(4,'Natural')))\nprint(\"Probability of having injury more than 42 days due to synthetic surface = \"+str(count_probability(4,'Synthetic')))\nprint(\"--------------------------\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"\ninjury_data.groupby(['DM_M_Total','BodyPart']) \\\n    .count().unstack('DM_M_Total')['PlayerKey'].T.sort_values('DM_M_Total').T.plot(kind='bar',figsize=(10,7),title='Injury happened for days by Bodypart')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"markdown","source":"### IF player get injury at knee then it more likely that  injury will stay for more than 7 days"},{"metadata":{"trusted":true},"cell_type":"code","source":"injurywithplay=pd.merge(playlist,injury_data,on=['PlayKey','PlayerKey','GameID'])\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"incorrect_Stadium=['Outdoors','Oudoor','Indoors','Retr. Roof - Closed','Domed, closed']\ncorrect_stadium=[]\nfor types in injurywithplay['StadiumType'].values:\n    if types=='Outdoors':\n        correct_stadium.append('Outdoor')\n    elif types=='Outddors':\n        correct_stadium.append('Outdoor')\n    elif types=='Oudoor':\n        correct_stadium.append(\"Outdoor\")\n    elif types=='Indoors':\n        correct_stadium.append(\"Indoor\")\n    elif types=='Retr. Roof - Closed':\n        correct_stadium.append(\"Retr. Roof-Closed\")\n    elif types=='Domed, closed':\n        correct_stadium.append(\"Closed Dome\")\n    else:\n        correct_stadium.append(types)\ninjurywithplay['StadiumType']=correct_stadium","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"\ninjurywithplay.groupby(['StadiumType']).count()['PlayerKey']\\\n    .plot(kind='bar',figsize=(15,5),title='Injury happened by stadium type')\n\n \n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def count_probability(title,post):\n    num=injurywithplay[injurywithplay[title]==post]['PlayerKey'].count()\n    \n    prob=num/injurywithplay[title].count()\n    return round(prob*100,3)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"for types in injurywithplay['StadiumType'].unique():\n    print(\"Probability of \"+str(types)+ \" will get injuryed = \"+str(count_probability('StadiumType',types)))","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"You can notice that if player played in Outdoor stadium than there is more probability that it will get injured."},{"metadata":{"trusted":true},"cell_type":"code","source":"injurywithplay.groupby(['PlayType']).count()['PlayerKey']\\\n    .plot(kind='bar',figsize=(15,5),title='Injury happened by PlayType')\nfor ptype in injurywithplay['PlayType'].unique():\n    print(\"Probability of injury happened with their playtype \"+str(ptype)+\" = \"+str(count_probability(\"PlayType\",ptype)))","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Pass and Rush has more likely to get injured."},{"metadata":{"trusted":true},"cell_type":"code","source":"injurywithplay['injury_time']=injurywithplay['DM_M1']+injurywithplay['DM_M7']+injurywithplay['DM_M28']+injurywithplay['DM_M42']","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"injurywithplay.groupby(['RosterPosition','Surface'])\\\n    .count() \\\n    .unstack('RosterPosition')['PlayerKey']\\\n    .plot(kind='bar', figsize=(15, 5), title='Injury happend by their rosterposition')","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### CornerBack have more injury in synthetic surface than on natural surface and LineBacker has more injury on Natural surface than synthetic surface"},{"metadata":{"trusted":true},"cell_type":"code","source":"injurywithplay.groupby(['PlayType','Surface'])\\\n    .count() \\\n    .unstack('PlayType')['PlayerKey']\\\n    .plot(kind='bar', figsize=(15, 5), title='Injury happend by their PlayType')","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"#### You can see that sometype of playtype only get injury on synthetic surface only.Other have same possibility of having injury"},{"metadata":{"trusted":true},"cell_type":"code","source":"incorrect_weather=['Indoors',np.nan,'Coudy','Mostly sunny']\ncorrect_weather=[]\nfor weath in injurywithplay['Weather']:\n    if weath=='Indoors':\n        correct_weather.append('Indoor')\n    elif weath==np.nan:\n        correct_weather.append(\"Indoor\")\n    elif weath=='Coudy':\n        correct_weather.append(\"Cloudy\")\n    elif weath=='Mostly sunny':\n        correct_weather.append(\"Mostly Sunny\")\n    elif weath=='Clear skies':\n        correct_weather.append(\"Clear Skies\")\n    else:\n        correct_weather.append(weath)\ninjurywithplay['Weather']=correct_weather","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"injurywithplay.groupby(\"Weather\").count()['PlayerKey'].sort_values().plot(kind='barh',figsize=(5,8))\nfor weath in injurywithplay['Weather'].unique():\n    print(\"Probability of \"+str(weath)+\" will cause injury = \"+str(count_probability('Weather',weath)))","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Cloudy weather has more probability of get injury."},{"metadata":{"trusted":true},"cell_type":"code","source":"end_match=0\nearly_match=0\nmiddle_match=0\nfor weath in injurywithplay['PlayerGame'].unique():\n    if weath in range(1,11):\n        early_match += count_probability('PlayerGame',weath)\n    elif weath in range(11,21):\n        middle_match += count_probability(\"PlayerGame\",weath)\n    elif weath in range(21,31):\n        end_match += count_probability(\"PlayerGame\",weath)\n\nprint(\"Probability of injury happened at early stage of match = \"+str(round(early_match,2)))\nprint(\"Probability of injury happened at middle stage of match = \"+str(round(middle_match,2)))\nprint(\"Probability of injury happened at end stage of match = \"+str(end_match))\n","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"More Injury happened at start of matches."}],"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}