{"cells":[{"metadata":{},"cell_type":"markdown","source":"# NFL 1st and Future"},{"metadata":{},"cell_type":"markdown","source":"## Introduction<br/>\nThe National Football League is America's most popular sports league, comprised of 32 franchises that compete each year to win the Super Bowl, the world's biggest annual sporting event. Founded in 1920, the NFL developed the model for the successful modern sports league, including national and international distribution, extensive revenue sharing, competitive excellence, and strong franchises across the country.\nThe NFL is committed to advancing progress in the diagnosis, prevention and treatment of sports-related injuries. The NFL's ongoing health and safety efforts include support for independent medical research and engineering advancements and a commitment to work to better protect players and make the game safer, including enhancements to medical protocols and improvements to how our game is taught and played.\nAs more is learned, the league evaluates and changes rules to evolve the game and try to improve protections for players. Since 2002 alone, the NFL has made 50 rules changes intended to eliminate potentially dangerous tactics and reduce the risk of injuries.(NFL.com)"},{"metadata":{},"cell_type":"markdown","source":"## Kernel Problem<br/>\nThe objective of this kernel is to see if there is any impact of playing surfaces on players movement and performance that may increase the injury risk, and to find out if the injury risk is affected by other playing environment.","attachments":{}},{"metadata":{},"cell_type":"markdown","source":"## kernel methodology<br/>\nlots of research indicates that injury risk is not birth of moment, it depends on all previous and present environment. and this was the key of ,y analysis is to make aggregate comparison between player who has at least one injury in the past (100 in this datasets with 5 has repeated injuries) and player who has no injury in there past (150 players in this datasets), data visualizations is used to indentify any relationships between injury risk and playing environment and performance, logistic regression is used as evidence to prove the significant of this relationship.\n","attachments":{}},{"metadata":{"trusted":true,"_kg_hide-input":true,"_kg_hide-output":true},"cell_type":"code","source":"import pandas as pd\nimport numpy as np\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nfrom pandas import DataFrame\nimport matplotlib.colors as mcolors\nimport matplotlib.patheffects as path_effects\nfrom matplotlib import cm\nimport itertools\nfrom matplotlib.patches import Rectangle, Polygon\nfrom wordcloud import WordCloud, STOPWORDS, ImageColorGenerator\nfrom PIL import Image\nfrom textwrap import wrap\nimport re\nimport warnings\n\nimport os\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n        \nwarnings.filterwarnings('ignore')\n%matplotlib inline\nplt.style.use('default')\nkaggle_color = '#20beff'","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"playlist=pd.read_csv(\"/kaggle/input/nfl-playing-surface-analytics/PlayList.csv\")\ninjuryrecord=pd.read_csv(\"/kaggle/input/nfl-playing-surface-analytics/InjuryRecord.csv\")","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Analysis "},{"metadata":{},"cell_type":"markdown","source":"### Injury Type"},{"metadata":{"trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"# Define variable indicated number of missing training days for each injury\ninjuryrecord[\"DayMissingTraining\"]=injuryrecord[\"DM_M1\"]+injuryrecord[\"DM_M7\"]+injuryrecord[\"DM_M28\"]+injuryrecord[\"DM_M42\"]\ninjuryrecord[\"DayMissingTraining\"]=injuryrecord[\"DayMissingTraining\"].replace(4,42)\ninjuryrecord[\"DayMissingTraining\"]=injuryrecord[\"DayMissingTraining\"].replace(3,28)\ninjuryrecord[\"DayMissingTraining\"]=injuryrecord[\"DayMissingTraining\"].replace(2,7)\ninjuryrecord[\"DayMissingTraining\"]=injuryrecord[\"DayMissingTraining\"].replace(1,1)\n\n#Find number of players for each type of injury\ninjury1=pd.DataFrame(injuryrecord.groupby([\"PlayerKey\",\"BodyPart\"])[\"BodyPart\"].count().unstack().fillna(0))\n#Find number of missing training days for each injured player\ninjury2=pd.DataFrame(injuryrecord.groupby([\"PlayerKey\"])[\"DayMissingTraining\"].mean().fillna(0))\n\ninjury=pd.concat([injury1,injury2],axis=1)\n#Find number of injury \ninjury[\"NoInjury\"]=injury.Ankle+injury.Foot+injury.Heel+injury.Knee+injury.Toes\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"injuryrecord[\"BodyPart\"]=injuryrecord[\"BodyPart\"].astype(\"category\")\ninjuryrecord[\"BodyPart\"]=injuryrecord[\"BodyPart\"].cat.set_categories([\"Knee\",\"Ankle\",\"Toes\",\"Foot\",\"Heel\"])\n\ninjuryrecord[\"DayMissingTraining\"]=injuryrecord[\"DayMissingTraining\"].astype(\"category\")\ninjuryrecord[\"DayMissingTraining\"]=injuryrecord[\"DayMissingTraining\"].cat.set_categories([7,1,42,28])\ndef draw_border_around_axes(this_ax, color=\"black\"):\n    for axis in ['top','bottom','left','right']:\n        this_ax.spines[axis].set_visible(True)\n        this_ax.spines[axis].set_color(color)\n\ndef hide_axes(this_ax):\n    this_ax.set_frame_on(False)\n    this_ax.set_xticks([])\n    this_ax.set_yticks([])\n    return this_ax\n\nbarstyle = {\"edgecolor\":\"black\", \"linewidth\":0.5}\n\n        \nf, ax = plt.subplots(nrows=2, ncols=2, figsize=(9,9),gridspec_kw={'height_ratios':[2,5], 'width_ratios':[2,5], 'wspace':0.1, 'hspace':0.1})\nthis_ax = ax[0,0]\nhide_axes(this_ax)\n\nhm_ax = ax[1,1]\nsns.heatmap(pd.crosstab(injuryrecord[\"BodyPart\"],injuryrecord[\"DayMissingTraining\"]),annot=True, fmt=\"d\", square=False, \ncenter = 90, vmin=0, vmax=20, lw=4, cbar=False,color=\"black\")\nhm_ax.yaxis.tick_right()\nhm_ax.yaxis.set_label_position(\"right\")\ndraw_border_around_axes(hm_ax)\n\nthis_ax = ax[1,0]\ninjuryrecord.BodyPart.value_counts().to_frame().sort_values(by=\"BodyPart\").plot.barh(ax=this_ax,colors='darkseagreen',**barstyle)\nthis_ax.set_xlabel(\"BodyPart\")\nthis_ax.xaxis.tick_top()\nthis_ax.set_xlim(this_ax.get_xlim()[::-1]);\nthis_ax.yaxis.set_label_position(\"right\")\nthis_ax.xaxis.set_label_position(\"top\")\n\n\nthis_ax = ax[0,1]\ninjuryrecord.DayMissingTraining.value_counts().plot.bar(ax=this_ax,colors='peru',**barstyle)\nthis_ax.set_ylabel(\"MissingDays\")\nthis_ax.xaxis.set_label_position(\"bottom\")\nthis_ax.yaxis.set_label_position(\"left\")\nthis_ax.xaxis.tick_top()\n","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"There are two ways to classify our injuries<br/>\n**Body Type**: as you can see players are suffering the most from Knee and Ankle injuries with (85.7)%, where Toes, Foot and Heel are much less likely to happened.<br/>\n**Serious**: Other concern should be interesting is how serious is your injury is? and i used number of missing training days as indicator, notice that (64.8)% of injuries do not serious (less missing trainig days).<br/>\n\nNow if we look deeper into out charts you can notice that fortunetly (67.8)% of our comon injuries(Knee and Ankle) is not serious where (53.3)% of not common injuries are serious.<br/>\nSo i think there is good news for NFL that serious injuries are less likely to occured. "},{"metadata":{"trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"injuryrecord.groupby(['BodyPart','Surface']).count().unstack('BodyPart')['PlayerKey'].T.apply(lambda x: x).sort_values('BodyPart').T.sort_values(\"Knee\", ascending=False).plot(kind='barh',\n          figsize=(15, 5),\n          title='Injury Body Part by Field Type',\n          stacked=True)\nplt.show()\n","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"There are two things to highligh here<br/>\nPlayers are more likely to injured in stadiums with synthetic surface than natural<br/>\nFrom injury type perspective, Ankle and Toes is more likely to occurs in synthetic surface, where foot and heel is more likely to happened at natural surface.\n"},{"metadata":{},"cell_type":"markdown","source":"## Playing Environments","attachments":{}},{"metadata":{"trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"# Data cleaning\n#1-Stadium Type\nplaylist.StadiumType=playlist.StadiumType.replace([\"Outdoor\",\"Outdoors\",\"Oudoor\",\"Ourdoor\",\"Outdoor Retr Roof-Open\",\"Outddors\",\n                                                  \"Outdor\",\"Outside\",\"Open\",\"cloudy\",\"Cloudy\",\"Bowl\",\"Heinz Field\",\"Indoor, Open Roof\"\n                                                  ,\"Domed, open\",\"Domed, Open\",\"Retr. Roof - Open\",\"Retr. Roof-Open\",\"Open\"],\"Outdoor\")\nplaylist.StadiumType=playlist.StadiumType.replace([\"Indoors\",\"Indoor\",\"Indoor, Roof Closed\",\"Dome\",\"Domed, closed\",\"Dome, closed\",\"Closed Dome\",\n                                                   \"Domed\",\"Retractable Roof\",\"Retr. Roof - Closed\",\"Retr. Roof-Closed\",\"Retr. Roof Closed\"],\"Indoor\")\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"#2-Weather\nplaylist.Weather=playlist.Weather.replace([\"Cloudy\",\"Partly Cloudy\",\"Mostly Cloudy\",\"Partly Clouidy\",\"Coudy\",\n                                           \"Cloudy with periods of rain, thunder possible. Winds shifting to WNW, 10-20 mph.\",\n                                          \"Party Cloudy\",\"Cloudy, chance of rain\",\"Mostly cloudy\",\"Partly cloudy\",\"cloudy\",\"Cloudy and Cool\"\n                                          \"Cloudy, 50% change of rain\",\"Cloudy, fog started developing in 2nd quarter\",\n                                           \"Cloudy, 50% change of rain\",\"Cloudy and Cool\",\"Cloudy and cold\",\"Cloudy, light snow accumulating 1-3\",\n                                          \"Mostly Coudy\",\"Cloudy, light snow accumulating 1-3\",\"Hazy\",\"Overcast\"],\"Cloudy\")\nplaylist.Weather=playlist.Weather.replace([\"Sunny\",\"Mostly Sunny\",\"Partly Sunny\",\"Mostly sunny\",\"Sunny and clear\",\n                                           \"Sunny and warm\",\"Sunny, highs to upper 80s\",\"Sunny Skies\",\"Sunny, Windy\",\"Partly sunny\",\n                                           \"Clear and Sunny\",\"Sun & clouds\",\"Clear and sunny\",\"Mostly Sunny Skies\",\"Sunny and cold\"],\"Sunny\")\nplaylist.Weather=playlist.Weather.replace([\"Clear\",\"Clear and warm\",\"Clear Skies\",\"Clear skies\",\"Clear and cold\",\"Partly clear\",\n                                           \"Clear and Cool\",\"Clear to Partly Cloudy\",\"Fair\"],\"Clear\")\nplaylist.Weather=playlist.Weather.replace([\"N/A (Indoors)\",\"Indoors\",\"Indoor\",\"N/A Indoor\",\"Controlled Climate\"],\"Indoor\")\nplaylist.Weather=playlist.Weather.replace([\"Light Rain\",\"Scattered Showers\",\"Showers\",\"Rainy\",\"Rain shower\",\"Cloudy, Rain\",\n                                           \"Chance of Rain\",\"Rain likely, temps in low 40s.\",\"10% Chance of Rain\",\"Rain Chance 40%\",\n                                          \"30% Chance of Rain\"],\"Rain\")\nplaylist.Weather=playlist.Weather.replace([\"Heavy lake effect snow\",\"Snow\",'Cloudy, light snow accumulating 1-3\"'],\"Snow\")\nplaylist.Weather=playlist.Weather.replace([\"Cold\",\"Heat Index 95\"],\"Other\")\n\n#3-RosterPosition\nplaylist.RosterPosition=playlist.RosterPosition.replace([\"Offensive Lineman\"],\"Offensive_Lineman\")\nplaylist.RosterPosition=playlist.RosterPosition.replace([\"Wide Receiver\"],\"Wide_Receiver\")\nplaylist.RosterPosition=playlist.RosterPosition.replace([\"Defensive Lineman\"],\"Defensive_Lineman\")\nplaylist.RosterPosition=playlist.RosterPosition.replace([\"Running Back\"],\"Running_Back\")\nplaylist.RosterPosition=playlist.RosterPosition.replace([\"Tight End\"],\"Tight_End\")\n\n#4-PlayType\nplaylist.PlayType=playlist.PlayType.replace([\"0\"],\"None\")\n\n#5-playlist\nplaylist.PlayType=playlist.PlayType.replace([\"Extra Point\"],\"Extra-Point\")\nplaylist.PlayType=playlist.PlayType.replace([\"Field Goal\"],\"Field-Goal\")\nplaylist.PlayType=playlist.PlayType.replace([\"Kickoff Not Returned\"],\"Kickoff-Not-Returned\")\nplaylist.PlayType=playlist.PlayType.replace([\"Kickoff Returned\"],\"Kickoff-Returned\")\nplaylist.PlayType=playlist.PlayType.replace([\"Punt Not Returned\"],\"Punt-Not-Returned\")\nplaylist.PlayType=playlist.PlayType.replace([\"Punt Returned\"],\"Punt-Returned\")\n\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"# Missing data\n#stadium type\nplaylist[\"StadiumType\"].fillna(\"Outdoor\",inplace=True)\n# Weather and Temerature\nplaylist.Temperature.replace([-999],np.nan,inplace=True)\nplaylist[\"Weather\"]=playlist.groupby(\"StadiumType\").Weather.transform(lambda x: x.fillna(x.mode()[0]))\nplaylist[\"Temperature\"].fillna(playlist.groupby([\"StadiumType\",\"Weather\"])[\"Temperature\"].transform(np.median),inplace=True)\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"#split the playlist datasets into two sets one for inured players and other for non injured players\nInjplaylist=playlist[playlist.PlayerKey.isin(injuryrecord.PlayerKey)]\nInjplay=Injplaylist.dropna(axis=0)\nplay_noinjury=playlist[~playlist.PlayerKey.isin(injuryrecord.PlayerKey)]\nplay_noinjury.dropna(axis=0,inplace=True)\nplay_injury=pd.merge(Injplaylist,injuryrecord,on=[\"PlayerKey\",\"GameID\",\"PlayKey\"],how=\"outer\")\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"play_injury=play_injury.drop([\"DM_M1\",\"DM_M7\",\"DM_M28\",\"DM_M42\",\"DayMissingTraining\"],axis=1)\nplay_injury[\"BodyPart\"]=play_injury[\"BodyPart\"].astype(\"category\")\nplay_injury[\"BodyPart\"]=play_injury[\"BodyPart\"].cat.add_categories('None')\nplay_injury[\"BodyPart\"].fillna(\"None\",inplace=True)\nplay_injury.dropna(axis=0,inplace=True)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"play_injury[\"Injury_Risk\"]=1\nplay_noinjury[\"Injury_Risk\"]=0\ninjuryrisk=pd.concat([play_injury,play_noinjury],axis=0)\ninjuryrisk.drop([\"BodyPart\"],axis=1,inplace=True)\n\nrisk1=injuryrisk.groupby([\"PlayerKey\",\"RosterPosition\"])[\"RosterPosition\"].nunique().unstack().fillna(0).astype('int64')\nrisk4=injuryrisk.groupby([\"PlayerKey\",\"PlayType\"])[\"PlayType\"].count().unstack().fillna(0).astype('int64')\nrisk6=injuryrisk.groupby([\"PlayerKey\"])[\"PlayerGame\"].max().fillna(0).astype('int64')\nrisk7=injuryrisk.groupby([\"PlayerKey\"])[\"PlayerGamePlay\"].max().fillna(0).astype('int64')\nrisk8=injuryrisk.groupby([\"PlayerKey\"])[\"Temperature\"].max().fillna(0).astype('int64')\nrisk9=injuryrisk.groupby([\"PlayerKey\",\"FieldType\"])[\"FieldType\"].count().unstack().fillna(0).astype('int64')\nrisk10=injuryrisk.groupby([\"PlayerKey\",\"StadiumType\"])[\"StadiumType\"].count().unstack().fillna(0).astype('int64')\nrisk11=injuryrisk.groupby([\"PlayerKey\",\"Weather\"])[\"Weather\"].count().unstack().fillna(0).astype('int64')\nrisk12=injuryrisk.groupby([\"PlayerKey\"])[\"Injury_Risk\"].mean().fillna(0).astype('int64')\n\nfrom functools import reduce\ndfs = [risk1, risk4,risk6, risk7,risk8, risk9, risk10, risk11, risk12] # list of dataframes\ndf_final = reduce(lambda left,right: pd.merge(left,right,on='PlayerKey'), dfs)\n","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### 1- Roster Position "},{"metadata":{"trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"\nplt.figure(figsize=(20,8))\nplt.subplot(1,2,1)\ntext1=\" \".join(Injplay['RosterPosition'].str.lower())\nwordcloud = WordCloud(stopwords=STOPWORDS,background_color='white', max_words=300,collocations = False).generate(text1)\n# Display the generated image:\nplt.imshow(wordcloud, interpolation='bilinear')\nplt.title('Roster Position game play distribution for player with injury', fontsize=15)\nplt.axis(\"off\")\n\nplt.subplot(1,2,2)\ntext2=\" \".join(play_noinjury['RosterPosition'].str.lower())\nwordcloud = WordCloud(stopwords=STOPWORDS,background_color='white', max_words=300,collocations = False).generate(text2)\nplt.imshow(wordcloud, interpolation='bilinear')\nplt.title('Roster Position game play distribution for player with no injury', fontsize=15)\nplt.axis(\"off\")\nplt.show()\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"import statsmodels.api as sm\nx=df_final[['Cornerback', 'Defensive_Lineman', 'Kicker', 'Linebacker','Offensive_Lineman', 'Quarterback', 'Running_Back', 'Safety','Tight_End', 'Wide_Receiver']]\ny=df_final.Injury_Risk\nsm.Logit(y,x).fit().pvalues","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Our grapha suggest that players in Cornerback, Safety, Wide_Receiver and Linebacker position is more likely to be injured if they playing many games, in the contrary with offensive and defensive lineman .<br/>\nHowever our model couldn't fail to support if these postions is significant injury risk (This is for position only without number of game playing) but suggest that offensive and defensive lineman is the most safer position in football team.\n\n\n","attachments":{}},{"metadata":{},"cell_type":"markdown","source":"### 2- Play Type"},{"metadata":{"scrolled":true,"trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"plt.figure(figsize=(20,8))\nplt.subplot(1,2,1)\ntext1=\" \".join(Injplay['PlayType'].str.lower())\nwordcloud = WordCloud(stopwords=STOPWORDS,background_color='white', max_words=300,collocations = False).generate(text1)\n# Display the generated image:\nplt.imshow(wordcloud, interpolation='bilinear')\nplt.title('Play Type game play distribution for player with injury')\nplt.axis(\"off\")\n\nplt.subplot(1,2,2)\ntext2=\" \".join(play_noinjury['PlayType'].str.lower())\nwordcloud = WordCloud(stopwords=STOPWORDS,background_color='white', max_words=300,collocations = False).generate(text2)\nplt.imshow(wordcloud, interpolation='bilinear')\nplt.title('Play Type  game play distribution for player with no injury')\nplt.axis(\"off\")\n\nplt.show()\n\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"x=df_final[['Extra-Point', 'Field-Goal', 'Kickoff','Kickoff-Not-Returned', 'Kickoff-Returned', 'None', 'Pass', 'Punt',\n           'Punt-Not-Returned', 'Punt-Returned', 'Rush']]\ny=df_final.Injury_Risk\nsm.Logit(y,x).fit().pvalues","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Not Much to said here, our graphs and model suggest no significant association with injury risk for any type of playing.","attachments":{}},{"metadata":{},"cell_type":"markdown","source":"### 3- Weather"},{"metadata":{"trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"plt.figure(figsize=(20,8))\nplt.subplot(1,2,1)\ntext1=\" \".join(Injplay['Weather'].str.lower())\nwordcloud = WordCloud(stopwords=STOPWORDS,background_color='white', max_words=300,collocations = False).generate(text1)\n# Display the generated image:\nplt.imshow(wordcloud, interpolation='bilinear')\nplt.title('Weather distribution for player with injury',fontsize=15)\nplt.axis(\"off\")\n\nplt.subplot(1,2,2)\ntext2=\" \".join(play_noinjury['Weather'].str.lower())\nwordcloud = WordCloud(stopwords=STOPWORDS,background_color='white', max_words=300,collocations = False).generate(text2)\nplt.imshow(wordcloud, interpolation='bilinear')\nplt.title('Weather distribution for player with no injury',fontsize=15)\nplt.axis(\"off\")\nplt.show()\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"x=df_final[['Clear','Cloudy', 'Indoor_y', 'Other', 'Rain', 'Snow', 'Sunny']]\ny=df_final.Injury_Risk\nsm.Logit(y,x).fit().pvalues","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"This should be surprising since lots of previous research and study find strong association between weather and injury occurance espcially in rain and snow. "},{"metadata":{},"cell_type":"markdown","source":"### 4-Field Type"},{"metadata":{"trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"plt.figure(figsize=(20,8))\nplt.subplot(1,2,1)\nax1=Injplaylist.FieldType.value_counts().plot.barh(color=\"darkseagreen\")\nplt.gca().invert_xaxis()\nplt.title(\"Field Type game play distribution for injury players\",fontsize=15)\n\nplt.subplot(1,2,2)\nax2=play_noinjury.FieldType.value_counts().plot.barh(color=\"peru\")\nplt.title(\"Field Type game play distribution for non_injury players\",fontsize=15)\n\nplt.subplots_adjust(wspace=0.05)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"x=df_final[['Natural', 'Synthetic']]\ny=df_final.Injury_Risk\nsm.Logit(y,x).fit().pvalues","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Although many studies shows strong correlation between surface and injury but our result fail to support their findings to see that Field type has no affect on injury"},{"metadata":{},"cell_type":"markdown","source":"### 5- Stadium Type"},{"metadata":{"trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"plt.figure(figsize=(20,8))\nplt.subplot(1,2,1)\nax1=Injplaylist.StadiumType.value_counts().plot.barh(color=\"darkseagreen\")\nplt.gca().invert_xaxis()\nplt.title(\"Stadium Type game play distribution for injurt players\",fontsize=15)\n\nplt.subplot(1,2,2)\nax2=play_noinjury.StadiumType.value_counts().plot.barh(color=\"peru\")\nplt.title(\"Stadium Type game play distribution for non_injurt players\",fontsize=15)\n\nplt.subplots_adjust(wspace=0.05)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"x=df_final[[\"Indoor_x\",\"Outdoor\"]]\ny=df_final.Injury_Risk\nsm.Logit(y,x).fit().pvalues","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Although by logic Outdoor should be more associated with more injury since its more exposed to weather changing but out analysis is fail to support this assumption."},{"metadata":{},"cell_type":"markdown","source":"### 6-No of Game played"},{"metadata":{"trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"Nogame_injury=play_injury.groupby([\"PlayerKey\"])[\"PlayerGame\"].max().to_frame()\nNogame_injury.columns=[\"No.game.inj\"]\nNogame_noinjury=play_noinjury.groupby([\"PlayerKey\"])[\"PlayerGame\"].max().to_frame()\nNogame_noinjury.columns=[\"No.game.noinj\"]\n\nplt.figure(figsize=(20,8))\nplt.subplot(1,2,1)\nax1=Nogame_injury[\"No.game.inj\"].hist(color=\"darkseagreen\")\nplt.xlabel(\"Number of game\")\nplt.title(\"Number of games played by injured player\",fontsize=15)\n\nax2=plt.subplot(1,2,2)\nNogame_noinjury[\"No.game.noinj\"].hist(color=\"peru\")\nplt.xlabel(\"Number of game\")\nplt.title(\"Number of games played by non_injured player\",fontsize=15)\n\nplt.show()\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"x=df_final[[\"PlayerGame\"]]\ny=df_final.Injury_Risk\nsm.Logit(y,x).fit().pvalues","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Number of playing game should have high impact on injury occurance but here i gave big question marks on negative association here, from our charts the most of injury players had played less than 10 games where for most non_injury players had played more than 25 played. One explanation is injured player is missing many game in recovery and on the bench.\n"},{"metadata":{},"cell_type":"markdown","source":"### 7- Maximam number of game play"},{"metadata":{"trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"Nogameplay_injury=play_injury.groupby([\"PlayerKey\"])[\"PlayerGamePlay\"].max().to_frame()\nNogameplay_injury.columns=[\"No.gameplay.inj\"]\nNogameplay_noinjury=play_noinjury.groupby([\"PlayerKey\"])[\"PlayerGamePlay\"].max().to_frame()\nNogameplay_noinjury.columns=[\"No.gameplay.noinj\"]\n\nplt.figure(figsize=(20,8))\nplt.subplot(1,2,1)\nNogameplay_injury[\"No.gameplay.inj\"].hist(color=\"darkseagreen\")\nplt.xlabel(\"Maximum number of plays per game\")\nplt.title(\"Maximum number of plays per game played by injured player\",fontsize=15)\n\n\nplt.subplot(1,2,2)\nNogameplay_noinjury[\"No.gameplay.noinj\"].hist(color=\"peru\")\nplt.xlabel(\"Maximum number of plays per game\")\nplt.title(\"Maximum number of plays per game played by non_injured player\",fontsize=15)\n\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"x=df_final[\"PlayerGamePlay\"]\ny=df_final.Injury_Risk\nsm.Logit(y,x).fit().pvalues","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### 8- Temperature"},{"metadata":{"trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"Tem_injury=play_injury.groupby([\"PlayerKey\"])[\"Temperature\"].mean().to_frame()\nTem_injury.columns=[\"tem.mean.inj\"]\nTem_noinjury=play_noinjury.groupby([\"PlayerKey\"])[\"Temperature\"].mean().to_frame()\nTem_noinjury.columns=[\"tem.mean.noinj\"]\n\nplt.figure(figsize=(20,8))\nplt.subplot(1,2,1)\nTem_injury[\"tem.mean.inj\"].hist(color=\"darkseagreen\")\nplt.xlabel(\"Average Temperature\")\nplt.title(\"Temperature distribution in games played by injured players\",fontsize=15)\n\nplt.subplot(1,2,2)\nTem_noinjury[\"tem.mean.noinj\"].hist(color=\"peru\")\nplt.xlabel(\"Average Temperature\")\nplt.title(\"Temperature distribution in games played by non_injured players\",fontsize=15)\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"x=df_final[\"Temperature\"]\ny=df_final.Injury_Risk\nsm.Logit(y,x).fit().pvalues","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Higher Temperature means higher injury risk,Exposure to high temperatures can lead to physiological and psychological changes associated with heat strain, which in turn can decrease workers' performance and lead to impaired concentration, increased distractibility, and fatigue (Kjellstrom et al. 2016). so it is not surprising to see temperature is significantly associated with injury risk."},{"metadata":{},"cell_type":"markdown","source":"### PLayer Track "},{"metadata":{"trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"import dask.dataframe as dd\ntrack = dd.read_csv(\"/kaggle/input/nfl-playing-surface-analytics/PlayerTrackData.csv\")\ntrack[\"PlayerKey\"]=track[\"PlayKey\"].str[:5]\n\nplaytrack=track.groupby([\"PlayKey\"]).agg({\"x\":\"mean\",\"y\":\"mean\",\"dir\":\"mean\",\"dis\":\"mean\",\"o\":\"mean\",\"s\":\"mean\"}).compute()\nplay_track=pd.merge(playtrack,playlist,on=\"PlayKey\")\n","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### Positons"},{"metadata":{"trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"\nsns.catplot(y=\"FieldType\",x=\"x\",data=play_track,kind=\"boxen\")\n\nsns.catplot(y=\"FieldType\",x=\"y\",data=play_track,kind=\"boxen\")\nplt.show()\n","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### Distance and directions"},{"metadata":{"trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"\nsns.catplot(y=\"FieldType\",x=\"dir\",data=play_track,kind=\"boxen\")\n\nsns.catplot(y=\"FieldType\",x=\"dis\",data=play_track,kind=\"boxen\")","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### Speed and Acceleration"},{"metadata":{"trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"sns.catplot(y=\"FieldType\",x=\"o\",data=play_track,kind=\"boxen\")\n\nsns.catplot(y=\"FieldType\",x=\"s\",data=play_track,kind=\"boxen\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"playertrack=track.groupby([\"PlayerKey\"]).agg({\"x\":\"mean\",\"y\":\"mean\",\"dir\":\"mean\",\"dis\":\"mean\",\"o\":\"mean\",\"s\":\"mean\"}).compute()\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"playertrack.reset_index(inplace=True)\ndf_final.reset_index(inplace=True)\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"df_final.PlayerKey = df_final.PlayerKey.astype(\"object\")\nplayer_track=pd.concat([df_final[\"Injury_Risk\"],playertrack],axis=1)\nplayer_track.dropna(axis=0,inplace=True)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"x = player_track.drop([\"Injury_Risk\",\"PlayerKey\"],axis=1)\ny = player_track.Injury_Risk\nsm.Logit(y,x).fit().pvalues","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Its abvious that playing surface had no affect on any of players movements or positions, and no players movements and positions have significant impact on injury risk."},{"metadata":{"trusted":true},"cell_type":"markdown","source":"## Data Limitations\n1. about (27)% of injuries which is great proportion has no available information about their playing environment or player track data and hence impact on the study findings\n2. Other information about players should be gather like their age, weight, height, medical history, training sessions and many other things.\n3. The data should be gather on dates so we can indentify so we can indentify to capture more information like,how many days between games.\n\n","attachments":{}},{"metadata":{},"cell_type":"markdown","source":"## Conclusion\nInjuries in Football has huge impact on team performance and cost millions for players treatment and find proper player replacement, so many research is conducted to find the main factors that increase the injury risk.<br/>\nThe most common injuries are knee and ankle injuries but luckily most of these injuries are not serious, most of these injuries occurred in stadiums with synthetics surface, although there is significant impact of playing surfaces on players movement and positions<br/>\nOur analysis that number of game playing, maximum number of game play and temperature has significant impact on injuries, and we found that offensive and defensive lineman is the safer positions among all team square.\n","attachments":{}},{"metadata":{"trusted":true},"cell_type":"markdown","source":"## Recommendation\nAlthough Football injury is inevitable but there is some consideration should be taken into account to reduce its risk and impact\n1. Examination of stadiums conditions periodically especially the ones with synthetics surface.\n2. Pay attention to environmental recommendations, especially in relation to excessively hot and humid weather, to help avoid heat illness\n3. Maintain proper fitness — injury rates are higher in athletes who have not adequately prepared physically.\n4. Don't hesitate to Speak with a sports medicine professional for any concerns about injuries or injury prevention strategies\n","attachments":{}}],"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.3"}},"nbformat":4,"nbformat_minor":1}