{"cells":[{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"# This Python 3 environment comes with many helpful analytics libraries installed\n# It is defined by the kaggle/python docker image: https://github.com/kaggle/docker-python\n# For example, here's several helpful packages to load in \n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\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":{},"cell_type":"markdown","source":"# --------------------NFL Surface Analytics-------------\n# -------------------[By Anurag Aiyer]------------------"},{"metadata":{},"cell_type":"markdown","source":"## The NFL is currently interested in seeing the factors that different playing surfaces have towards player performance and injury. In this notebook, we will be conducting exploratory analysis to solidify and understand the issues that ascertain towards key categorization of factors toward injuries. The goal is to try to gain an understanding into how we can find relationships between injuries and NFL turfs efficient, so that we can try to create a better understanding and perspective of how better regulations can be implemented. As of right now, there are concussion-sustained injuries that virtually last a life time and there is not much physicians or sport health specialists that can address the complete root cause."},{"metadata":{},"cell_type":"markdown","source":"# Here is the following breakdown of the notebook:\n1. Looking at the different frequency of injuries for each player. What is the general outlook overall?\n   \n2. Understanding or viewing any association between surfaces and injuries\n\n3. Potentially discovering any classifications or further interpretations of the data that can be made\n\n4. Maybe viewing fluctuations or other alternatives that could be considered to enforcing strict NFL protocols"},{"metadata":{},"cell_type":"markdown","source":"# **[1]** MOST FREQUENT INJURIES FOR EACH POSITION"},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"#READING all the csv downloaded from Kaggle API\nimport matplotlib.pyplot as plt\nimport matplotlib.ticker as ticker\nimport matplotlib.cm as cmap\nimport seaborn as sns ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"playerlist = pd.read_csv('/kaggle/input/nfl-playing-surface-analytics/PlayList.csv')\ninjury_record = pd.read_csv('/kaggle/input/nfl-playing-surface-analytics/InjuryRecord.csv')\ntrackerdata = pd.read_csv('/kaggle/input/nfl-playing-surface-analytics/PlayerTrackData.csv')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"relationship = playerlist.drop_duplicates('PlayerKey', keep='first').merge(injury_record, on='PlayerKey')\nrelationship['RosterPosition'].value_counts().plot(kind='bar', title='INJURIES VS Position of Player')","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Out of **105** injured players within the past 2 seasons, it is clear that the two positions for the highest number of injuries are **WIDE RECEIVER** and **LINEBACKER**. Majority of those injuries are either knee or ankle cases."},{"metadata":{},"cell_type":"markdown","source":"## Let us **view** the relationship between each position and specific injuries"},{"metadata":{"trusted":true},"cell_type":"code","source":"df = relationship[['RosterPosition','Surface','BodyPart']]\ndfnew = df.groupby(['RosterPosition', 'BodyPart']).count()\n#\n#result = df.pivot(index='Surface', columns='RosterPosition', values='value')\ndfrev = dfnew['Surface'].reset_index().rename(columns={'Surface':'Count'})\nax = sns.heatmap(dfrev.pivot_table(index='RosterPosition', columns = 'BodyPart', values='Count'))","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Linebackers have taken a major beating in terms of facing adversity and not fully rebouncing or recovering from the depths of injuries. It is important to understad other features as well that affect health well-being."},{"metadata":{},"cell_type":"markdown","source":"# **[2]** NFL SURFACES CONTRIBUTION TO INJURIES"},{"metadata":{},"cell_type":"markdown","source":"# Here is a relationship between RosterPosition and the different surfaces that reflects how injuries are happening. We can conclude that synthetic surfaces have more potential injuries than natural surfaces. This is especially the case for cornerbacks.\n\n"},{"metadata":{"trusted":true},"cell_type":"code","source":"surfaceinjuries = relationship[['RosterPosition', 'Surface']].groupby(['RosterPosition', 'Surface']).size().reindex()\nlst = []\nlsttwo = []\ncounter = 0\ncountertwo = 1\n#Natural Surface Injuries  \nwhile counter < len(surfaceinjuries):\n    lst.append(int(surfaceinjuries[counter]))\n    counter = counter + 2\n    \n    \n#Synthetic Surface Injuries\nwhile countertwo < len(surfaceinjuries)+1:\n    lsttwo.append(surfaceinjuries[countertwo])\n    countertwo = countertwo + 2\n    \n# set width of bar\nbarWidth = 0.25\n \n# set height of bar\nbars1 = lst\nbars2 = lsttwo\n \n# Set position of bar on X axis\nr1 = np.arange(len(bars1))\nr2 = [x + barWidth for x in r1]\nr3 = [x + barWidth for x in r2]\n \n# Make the plot\nplt.bar(r1, bars1, color='#7f6d5f', width=barWidth, edgecolor='white', label='Natural')\nplt.bar(r2, bars2, color='#557f2d', width=barWidth, edgecolor='white', label='Synthetic')\n#plt.bar(r3, bars3, color='#2d7f5e', width=barWidth, edgecolor='white', label='var3')\n \n# Add xticks on the middle of the group bars\nplt.xlabel('Position', fontweight='bold')\nplt.ylabel('Injuries', fontweight='bold')\n\nplt.xticks([r + barWidth for r in range(len(bars1))], ['Cornerback', 'Defensive Lineman', 'Linebacker', 'Offensive Lineman', 'Running Back', 'Safety', 'Tight End', 'Wide Receiver'])\n\nplt.xticks(rotation='vertical')\nplt.title('NFL Surface Lower-Limb Injuries', fontweight='bold')\n# Create legend & Show graphic\nplt.legend()\nplt.show()\n\n\n#Creating Stacked Bar with SurfaceInjuries among Lower-Limb NFL candidates\n#relationship[['RosterPosition', 'Surface']].groupby(['RosterPosition', 'Surface'])\n    \n#for x in range(0, len(surfaceinjuries), 2):\n    #natural = lst.append(surfaceinjuries[x])\n#list(surfaceinjuries.to_frame().columns)\n","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Since we went through a general rundown of how RosterPositions and injuries have a few associations, now let us further explore and deepen our understanding with how NFL turfs are affecting player movement. Some potential factors to think about our whether the speed or orientation is impacting the movement through a turf. If so,does higher velocity speed or a larger angle of inclination with respect to the ground emphasize a potential concern for injuries. In fact, what would be the minimum orientation such that a player would sustain a lower-limb injury? Realistically, this raises speculations to what kind of improvements can be made so that NFL players are much safer on the field. "},{"metadata":{},"cell_type":"markdown","source":"# With a few questions of these in mind, let's start our analysis. \n\n"},{"metadata":{},"cell_type":"markdown","source":"# **[3]** DISCOVERY STAGE"},{"metadata":{"trusted":true},"cell_type":"code","source":"numplays = trackerdata.groupby('PlayKey').size().to_frame().reset_index()\ninjury_record\nmerged_set = pd.merge(injury_record, numplays, on='PlayKey')\n#For 77 NFL lower-limb injures, looking at any possible trends or other signficant factors that highly affect the outcome\n#of the total # of plays and number of days missed during practices\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"merged_set['sum'] = merged_set.iloc[:,5:9].sum(axis = 1)\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"missed_time = []\nfor x in merged_set['sum']:\n    if x == 4:\n        missed_time.append('DM_42')\n    elif x == 3:\n        missed_time.append('DM_28')\n    elif x == 2:\n        missed_time.append('DM_7')\n    else:\n        missed_time.append('DM_1')\nmerged_set['NumDaysMissed'] = missed_time\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"missed_time","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Average Number of Plays for Day of Missed Games(77 injured players)\n"},{"metadata":{"trusted":true},"cell_type":"code","source":"merged_set = merged_set.iloc[:, [9, 11]].groupby('NumDaysMissed').mean()\n\n\n\n\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"merged_set.reindex().rename(columns={'0':'AverageNumPlays'}).plot(kind='bar', title='Average Plays and Relationship with Num Days Missed for Injured NFL Players', legend=None)\nplt.xlabel('NumDaysMissed')\nplt.ylabel('AveragePlays')\n","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# There seems to be a positive association between the number of days missed from participating in NFL games and the average number of plays injured players participated in a particular game. It would be interesting to intertwine and look at further examples for safety measurements. Now, it is imperative to view how orientation of an average play is measured and constructed with respect to the speed of a particular individual."},{"metadata":{"trusted":true},"cell_type":"code","source":"numplays = trackerdata.groupby('PlayKey').size().to_frame().reset_index()\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"trackerdata","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"playerlist","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"playerlist['PlayType']","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"injury_record","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"playerlist.loc[playerlist['PlayerKey']==26624]","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Most played fieldtypes that reflect the current atmosphere and different feel into the various fieldtypes. As an expample, we were able to find how we could figure the way in which FieldType provides useful insights into how different stadiums affect the larger chaos the world seems to be undergoing. "},{"metadata":{"trusted":true},"cell_type":"code","source":"playerlist.iloc[:, [ 6, 7]].groupby(['StadiumType']).count().reset_index().sort_values(by='FieldType', ascending=False).iloc[0:5].set_index('StadiumType').plot.bar(y='FieldType', rot=0)\n","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# There is some research that has provided further segway into he we could manipulate and get something fotunate about our life. Something to be cognizant about is the vulnerability for NFL players to be prone to inury until somethinbg possibly fes around out. I'm sure that the NFL injured citizens will not take anything granted. This is a place of development and belief in yoursef. "},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]}],"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"pygments_lexer":"ipython3","nbconvert_exporter":"python","version":"3.6.4","file_extension":".py","codemirror_mode":{"name":"ipython","version":3},"name":"python","mimetype":"text/x-python"}},"nbformat":4,"nbformat_minor":1}