{"cells":[{"metadata":{},"cell_type":"markdown","source":"![](http://d29m18w01sxjzp.cloudfront.net/source/2018/NFL/August/MooreDavid.jpg)"},{"metadata":{},"cell_type":"markdown","source":"**In this challenge, we have been 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.**\n## The Challenge\n**In the NFL, 12 stadiums have fields with synthetic turf. Recent investigations of lower limb injuries among football athletes have indicated significantly higher injury rates on synthetic turf compared with natural turf (Mack et al., 2018; Loughran et al., 2019). In conjunction with the epidemiologic investigations, biomechanical studies of football cleat-surface interactions have shown that synthetic turf surfaces do not release cleats as readily as natural turf and may contribute to the incidence of non-contact lower limb injuries (Kent et al., 2015). Given these differences in cleat-turf interactions, it has yet to be determined whether player movement patterns and other measures of player performance differ across playing surfaces and how these may contribute to the incidence of lower limb injury.**\n**Our challenge is to characterize any differences in player movement between the playing surfaces and identify specific scenarios (e.g., field surface, weather, position, play type, etc.) that interact with player movement to present an elevated risk of injury.**"},{"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.pylab as plt\nimport matplotlib.patches as patches\nimport seaborn as sns\nsns.set_style(\"darkgrid\")\npd.set_option('display.max_rows', 1000)\nimport plotly.graph_objects as go\nfrom plotly.subplots import make_subplots\n\nfrom plotly.offline import download_plotlyjs, init_notebook_mode,  iplot\ninit_notebook_mode(connected=True)\n\npd.options.mode.chained_assignment = None\n# Input data files are available in the \"../input/\" directory.\n# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\n\nimport os\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n\n# Any results you write to the current directory are saved as output.","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"# Plot the Football Field.\n# Source: https://www.kaggle.com/robikscube/nfl-big-data-bowl-plotting-player-position\ndef create_football_field(linenumbers=True,\n                          endzones=True,\n                          highlight_line=False,\n                          highlight_line_number=50,\n                          highlighted_name='Line of Scrimmage',\n                          fifty_is_los=False,\n                          figsize=(12, 6.33)):\n    \"\"\"\n    Function that plots the football field for viewing plays.\n    Allows for showing or hiding endzones.\n    \"\"\"\n    rect = patches.Rectangle((0, 0), 120, 53.3, linewidth=0.1,\n                             edgecolor='r', facecolor='darkgreen', zorder=0)\n\n    fig, ax = plt.subplots(1, figsize=figsize)\n    ax.add_patch(rect)\n\n    plt.plot([10, 10, 10, 20, 20, 30, 30, 40, 40, 50, 50, 60, 60, 70, 70, 80,\n              80, 90, 90, 100, 100, 110, 110, 120, 0, 0, 120, 120],\n             [0, 0, 53.3, 53.3, 0, 0, 53.3, 53.3, 0, 0, 53.3, 53.3, 0, 0, 53.3,\n              53.3, 0, 0, 53.3, 53.3, 0, 0, 53.3, 53.3, 53.3, 0, 0, 53.3],\n             color='white')\n    if fifty_is_los:\n        plt.plot([60, 60], [0, 53.3], color='gold')\n        plt.text(62, 50, '<- Player Yardline at Snap', color='gold')\n    # Endzones\n    if endzones:\n        ez1 = patches.Rectangle((0, 0), 10, 53.3,\n                                linewidth=0.1,\n                                edgecolor='r',\n                                facecolor='blue',\n                                alpha=0.2,\n                                zorder=0)\n        ez2 = patches.Rectangle((110, 0), 120, 53.3,\n                                linewidth=0.1,\n                                edgecolor='r',\n                                facecolor='blue',\n                                alpha=0.2,\n                                zorder=0)\n        ax.add_patch(ez1)\n        ax.add_patch(ez2)\n    plt.xlim(0, 120)\n    plt.ylim(-5, 58.3)\n    plt.axis('off')\n    if linenumbers:\n        for x in range(20, 110, 10):\n            numb = x\n            if x > 50:\n                numb = 120 - x\n            plt.text(x, 5, str(numb - 10),\n                     horizontalalignment='center',\n                     fontsize=20,  # fontname='Arial',\n                     color='white')\n            plt.text(x - 0.95, 53.3 - 5, str(numb - 10),\n                     horizontalalignment='center',\n                     fontsize=20,  # fontname='Arial',\n                     color='white', rotation=180)\n    if endzones:\n        hash_range = range(11, 110)\n    else:\n        hash_range = range(1, 120)\n\n    for x in hash_range:\n        ax.plot([x, x], [0.4, 0.7], color='white')\n        ax.plot([x, x], [53.0, 52.5], color='white')\n        ax.plot([x, x], [22.91, 23.57], color='white')\n        ax.plot([x, x], [29.73, 30.39], color='white')\n\n    if highlight_line:\n        hl = highlight_line_number + 10\n        plt.plot([hl, hl], [0, 53.3], color='yellow')\n        plt.text(hl + 2, 50, '<- {}'.format(highlighted_name),\n                 color='yellow')\n    return fig, ax","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"def reduce_mem_usage(df):\n    \"\"\" iterate through all the columns of a dataframe and modify the data type\n        to reduce memory usage.        \n    \"\"\"\n    start_mem = df.memory_usage().sum() / 1024**2\n    print('Memory usage of dataframe is {:.2f} MB'.format(start_mem))\n    \n    for col in df.columns:\n        col_type = df[col].dtype\n        \n        if col_type != object:\n            c_min = df[col].min()\n            c_max = df[col].max()\n            if str(col_type)[:3] == 'int':\n                if c_min > np.iinfo(np.int8).min and c_max < np.iinfo(np.int8).max:\n                    df[col] = df[col].astype(np.int8)\n                elif c_min > np.iinfo(np.int16).min and c_max < np.iinfo(np.int16).max:\n                    df[col] = df[col].astype(np.int16)\n                elif c_min > np.iinfo(np.int32).min and c_max < np.iinfo(np.int32).max:\n                    df[col] = df[col].astype(np.int32)\n                elif c_min > np.iinfo(np.int64).min and c_max < np.iinfo(np.int64).max:\n                    df[col] = df[col].astype(np.int64)  \n            else:\n                if c_min > np.finfo(np.float16).min and c_max < np.finfo(np.float16).max:\n                    df[col] = df[col].astype(np.float16)\n                elif c_min > np.finfo(np.float32).min and c_max < np.finfo(np.float32).max:\n                    df[col] = df[col].astype(np.float32)\n                else:\n                    df[col] = df[col].astype(np.float64)\n        else:\n            df[col] = df[col].astype('category')\n\n    end_mem = df.memory_usage().sum() / 1024**2\n    print('Memory usage after optimization is: {:.2f} MB'.format(end_mem))\n    print('Decreased by {:.1f}%'.format(100 * (start_mem - end_mem) / start_mem))\n    \n    return df\n\ndef import_data(file):\n    \"\"\"create a dataframe and optimize its memory usage\"\"\"\n    df = pd.read_csv(file, parse_dates=True, keep_date_col=True)\n    df = reduce_mem_usage(df)\n    return df","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# 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":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true,"_kg_hide-input":true,"_kg_hide-output":true},"cell_type":"code","source":"InjuryRecord = import_data(\"../input/nfl-playing-surface-analytics/InjuryRecord.csv\")\nPlayList = import_data(\"../input/nfl-playing-surface-analytics/PlayList.csv\")\nPlayerTrackData = import_data(\"../input/nfl-playing-surface-analytics/PlayerTrackData.csv\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"# StadiumType corrections\nstadium_dict = {\"Oudoor\" : \"Outdoor\", \"Outdoors\" : \"Outdoor\", \"Outdor\" : \"Outdoor\", \"Ourdoor\" : \"Outdoor\", \n                \"Outdoor Retr Roof-Open\" : \"Outdoor\", \"Open\" : \"Outdoor\", 'Outdoor Retr Roof-Open' : \"Outdoor\",\n                \"Outddors\" : \"Outdoor\", 'Retr. Roof-Open' : \"Outdoor\",  \"Indoor, Open Roof\" : \"Outdoor\", \"Heinz Field\" : \"Outdoor\",\n                 \"Domed, Open\" : \"Outdoor\", \"Domed, open\" : \"Outdoor\", 'Retr. Roof - Open' : \"Outdoor\", \"Outside\" : \"Outdoor\",\n                \"Closed Dome\" : \"Indoor\", \"Domed, closed\" : \"Indoor\", \"Dome\" : \"Indoor\", \"Domed\" : \"Indoor\", \n                \"Indoors\" : \"Indoor\", 'Retr. Roof-Closed' : \"Indoor\", \"Retractable Roof\" : \"Indoor\",  'Indoor, Roof Closed' : \"Indoor\",\n                \"Retr. Roof - Closed\" : \"Indoor\", 'Dome, closed' : \"Indoor\", \"Retr. Roof Closed\" : \"Indoor\", \"nan\" : np.NaN, 'Cloudy' : np.NaN}\n\n# Weather corrections\nweather_dict = {\"Indoors\" : \"Indoor\", \"N/A (Indoors)\": \"Indoor\", \"Clear skies\" : \"Clear\", \"Clear Skies\" : \"Clear\",\n                \"Clear and cold\" : \"Clear\", 'Cloudy, light snow accumulating 1-3\"' : \"Cloudy\",\n                \"Rain shower\" : \"Rain\", \"Cloudy, 50% change of rain\" : \"Cloudy\", \"Clear and warm\" : \"Clear\", \n                \"Cloudy with periods of rain\" : \"Cloudy\", \"Light Rain\" : \"Rain\", \"Light rain\" : \"Rain\", 'Rain Chance 40%' : \"Cloudy\",\n                \"Mostly sunny\" : \"Sunny\", \"Mostly Sunny\" : \"Sunny\", \"Sun & clouds\" : \"Sunny\", \"Partly Cloudy\" : \"Cloudy\",\n                \"Partly cloudy\" : \"Cloudy\", \"Coudy\" : \"Cloudy\", \"Party Cloudy\" : \"Cloudy\", \"Mostly Cloudy\" : \"Cloudy\",\n                \"Mostly cloudy\" : \"Cloudy\", \"Cloudy, 50% change of rain\" : \"Cloudy\", \"Cloudy and Cool\" : \"Cloudy\" , \"nan\" : np.NaN,\n               'Cloudy, fog started developing in 2nd quarter' : \"Cloudy\", 'N/A Indoor' : \"Indoor\", 'Rain likely, temps in low 40s.' : \"Rain\",\n               'Mostly Coudy' : \"Cloudy\", 'Scattered Showers' : \"Showers\", 'Heavy lake effect snow' : \"Snow\", 'Sunny Skies' : \"Sunny\",\n               'Partly clear' : \"Clear\", 'Sunny, Windy' : \"Sunny\", 'cloudy' : \"Cloudy\", 'Sunny, highs to upper 80s' : \"Sunny\",\n               'Cloudy with periods of rain, thunder possible. Winds shifting to WNW, 10-20 mph.' : \"Cloudy\", '10% Chance of Rain' : \"Cloudy\",\n               '30% Chance of Rain' : \"Cloudy\", 'Mostly Sunny Skies' : \"Sunny\", 'Rainy' : \"Rain\", 'Cloudy, chance of rain' : \"Cloudy\",\n               'Partly Clouidy' : \"Cloudy\", 'Partly Sunny' : \"Sunny\", 'Partly sunny' : \"Sunny\", 'Cloudy, Rain' : \"Rain\",\n               'Clear and sunny' : \"Clear and Sunny\", 'Clear and Cool' : \"Clear and Cold\", 'Heat Index 95' : \"Sunny\", 'Clear to Partly Cloudy' : \"Clear\",\n               'Clear and Cold' : 'Clear and cold'}\n\n# Revert Days Missed to the Original\ndays_missed_dict = {1 : \"1+\", 2: \"7+\", 3 : \"28+\", 4 : \"42+\"}\n\nPlayList[\"StadiumType\"] = PlayList[\"StadiumType\"].astype(str)\nPlayList[\"StadiumType\"].replace(stadium_dict, inplace=True)\nPlayList[\"Weather\"] = PlayList[\"Weather\"].astype(str)\nPlayList[\"Weather\"].replace(weather_dict, inplace=True)\nPlayList[\"PlayType\"] = PlayList[\"PlayType\"].replace('0', np.NaN)\nInjuryRecord['DaysMissed'] = InjuryRecord['DM_M1'] + InjuryRecord['DM_M7'] + InjuryRecord['DM_M28'] + InjuryRecord['DM_M42']\nInjuryRecord['DaysMissed'] = InjuryRecord[\"DaysMissed\"].map(days_missed_dict)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_kg_hide-input":true,"_kg_hide-output":true},"cell_type":"code","source":"InjuryRecord.head()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Injury Data and EDA\nFirst lets look at the injury data. It's a fairly small file with only 105 injury plays shown. I notice that many of the rows for the injury plays do not show PlayerKey, GameId, etc. I'm not sure if this is a bug or intentially done. So we have only 77 injury plays with playerkeys.\n\nPlayerKey, GameId, PlayKey\nBodyPart\nSurface\nDM_M1, DM_M7, DM_28, DM_42 - One hot encoding the number of days missed for injury"},{"metadata":{"_kg_hide-input":true,"trusted":true},"cell_type":"code","source":"import random\ndef random_colors(number_of_colors):\n    color = [\"#\"+''.join([random.choice('0123456789ABCDEF') for j in range(6)])\n                 for i in range(number_of_colors)]\n    return color","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"fig = make_subplots(\n    rows=1, cols=2,\n    specs=[[{\"type\": \"xy\"}, {\"type\": \"xy\"}]],\n    shared_xaxes=True, shared_yaxes=True,\n                    vertical_spacing=1,\n                    subplot_titles = (' Body Parts', \n                                      ' Turf'))\n\npitch_count = InjuryRecord['BodyPart'].value_counts()\nsurface_count = InjuryRecord['Surface'].value_counts()\n\nfig.add_trace(go.Bar(y=pitch_count.values,x=pitch_count.index,hoverinfo='y',marker = dict(color = random_colors(25))),\n              row=1, col=1)\n\nfig.add_trace(go.Bar(y=surface_count.values,x=surface_count.index,hoverinfo='y',marker = dict(color = random_colors(25))),\n              row=1, col=2)\n\n\n\nfig.update_layout(height=600,width=800,title=\" Injuries by Body parts and Turf\",title_x=0.5, showlegend=False)\n\nfig.show()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"**Conclusions**\n* Knees and Ankle injuries are more common event happened in the given data, almost covering up 85% of the injuries, it probably due to reason of low tackling and body joints. \n* Synthetic turf has more injuries but not much more than Natural turf so can't say for sure that the pitch has something to do with it. \n* Toes and Foot injuries are very rare which isn't surprising as the impact regions doesn't involve these parts mostly\n\n"},{"metadata":{},"cell_type":"markdown","source":"![](https://blog.muellersportsmed.com/hs-fs/hubfs/Mueller-Sports-Medicine-Blog-Most-Common-NFL-Injuries-Infographic.gif?width=1167&height=1803&name=Mueller-Sports-Medicine-Blog-Most-Common-NFL-Injuries-Infographic.gif)\n                 *Most Common Injuries according to MuellerSportsMed*"},{"metadata":{"trusted":true,"_kg_hide-input":true,"_kg_hide-output":true},"cell_type":"code","source":"PlayList.head()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"**Let's look at the Non Injury related distribution looks like  **"},{"metadata":{"_kg_hide-output":false,"trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"fig = make_subplots(rows=1, cols=6,specs=[[{\"type\": \"xy\"}, {\"type\": \"xy\"}, {\"type\": \"xy\"},{\"type\": \"xy\"}, {\"type\": \"xy\"}, {\"type\": \"xy\"}]],\n    shared_xaxes=True, shared_yaxes=True,\n                    vertical_spacing=1,\n                    subplot_titles = (' Roster Positions', \n                                      ' Stadium Type',\n                                      'Field Type',\n                                      'Weather',\n                                      'Play Type',\n                                      'Position'))\nrp_count = PlayList['RosterPosition'].value_counts()\nstadium_count = PlayList['StadiumType'].value_counts()\nfield_count = PlayList['FieldType'].value_counts()\nweather_count = PlayList['Weather'].value_counts()\nplay_count = PlayList['PlayType'].value_counts()\nposition_count = PlayList['Position'].value_counts()\n\nfig.add_trace(go.Bar(y=rp_count.values,x=rp_count.index,hoverinfo='y',marker = dict(color = random_colors(25))),\n              row=1, col=1)\n\nfig.add_trace(go.Bar(y=stadium_count.values,x=stadium_count.index,hoverinfo='y',marker = dict(color = random_colors(25))),\n              row=1, col=2)\n\nfig.add_trace(go.Bar(y=field_count.values,x=field_count.index,hoverinfo='y',marker = dict(color = random_colors(25))),\n              row=1, col=3)\n\nfig.add_trace(go.Bar(y=weather_count.values,x=weather_count.index,hoverinfo='y',marker = dict(color = random_colors(25))),\n              row=1, col=4)\n\nfig.add_trace(go.Bar(y=play_count.values,x=play_count.index,hoverinfo='y',marker = dict(color = random_colors(25))),\n              row=1, col=5)\n\nfig.add_trace(go.Bar(y=position_count.values,x=position_count.index,hoverinfo='y',marker = dict(color = random_colors(25))),\n              row=1, col=6)\n\nfig.update_layout(height=600,width=1000,title=\" All Non injury play data distribution\",title_x=0.5, showlegend=False)\n\nfig.show()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"**Conclusions**\n* Linebackers are mostly involved in a play data.\n* Outdoors stadiums are the most occuring stadium types.\n* Natural turfs are more than Synthetic turfs in a general play but the injuries are happening more in Synthetic turfs so it's a point to be noted.\n* Cloudy weathers involves more into the play data.\n* Pass are most occuring event which is not a surprise as you've to make a pass or run through defense to gain the yards.\n* Wide reciever are mostly involved into the play data."},{"metadata":{"trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"Injury_games_play = InjuryRecord.merge(PlayList,\n                  on='PlayKey',\n                  how='left')","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"**Injury Play data Information of Non Null data **"},{"metadata":{"trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"# information about InjuryGamedata\nInjury_games_play.info()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_kg_hide-input":true,"_kg_hide-output":true},"cell_type":"code","source":"Injury_games_play","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"**Let's take a look at the Injury Play data Distribution**"},{"metadata":{"_kg_hide-output":false,"trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"fig = make_subplots(\n    rows=1, cols=8,\n    specs=[[{\"type\": \"xy\"}, {\"type\": \"xy\"}, {\"type\": \"xy\"}, {\"type\": \"xy\"},{\"type\": \"xy\"}, {\"type\": \"xy\"}, {\"type\": \"xy\"}, {\"type\": \"xy\"}]],\n        shared_xaxes=True, shared_yaxes=True,\n                    vertical_spacing=1,\n                    subplot_titles = (' BodyPart',\n                                      'Surface',\n                                      'Roster Positions', \n                                      'Stadium Type',\n                                      'Field Type',\n                                      'Weather',\n                                      'Play Type',\n                                      'Position'))\npitch_count = Injury_games_play['BodyPart'].value_counts()\nsurface_count = Injury_games_play['Surface'].value_counts()\nrp_count = Injury_games_play['RosterPosition'].value_counts()\nstadium_count = Injury_games_play['StadiumType'].value_counts()\nfield_count = Injury_games_play['FieldType'].value_counts()\nweather_count = Injury_games_play['Weather'].value_counts()\nplay_count = Injury_games_play['PlayType'].value_counts()\nposition_count = Injury_games_play['Position'].value_counts()\n\nfig.add_trace(go.Bar(y=pitch_count.values,x=pitch_count.index,hoverinfo='y',marker = dict(color = random_colors(25))),\n              row=1, col=1)\n\nfig.add_trace(go.Bar(y=surface_count.values,x=surface_count.index,hoverinfo='y',marker = dict(color = random_colors(25))),\n              row=1, col=2)\n\nfig.add_trace(go.Bar(y=rp_count.values,x=rp_count.index,hoverinfo='y',marker = dict(color = random_colors(25))),\n              row=1, col=3)\n\nfig.add_trace(go.Bar(y=stadium_count.values,x=stadium_count.index,hoverinfo='y',marker = dict(color = random_colors(25))),\n              row=1, col=4)\n\nfig.add_trace(go.Bar(y=field_count.values,x=field_count.index,hoverinfo='y',marker = dict(color = random_colors(25))),\n              row=1, col=5)\n\nfig.add_trace(go.Bar(y=weather_count.values,x=weather_count.index,hoverinfo='y',marker = dict(color = random_colors(25))),\n              row=1, col=6)\n\nfig.add_trace(go.Bar(y=play_count.values,x=play_count.index,hoverinfo='y',marker = dict(color = random_colors(25))),\n              row=1, col=7)\n\nfig.add_trace(go.Bar(y=position_count.values,x=position_count.index,hoverinfo='y',marker = dict(color = random_colors(25))),\n              row=1, col=8)\n\nfig.update_layout(height=600,width=1200, title=\" All injury data distribution\",title_x=0.5,showlegend=False)\n\nfig.show()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"**Conclusions**\n* Synthetic turfs at large so there's something concerning about these turfs.\n* All other data distribution are in same proportion as in Non Injury related data.\n"},{"metadata":{},"cell_type":"markdown","source":"**What are the Body parts which gets injured most due to the different turfs?**"},{"metadata":{"trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"Injury_games_play.groupby('BodyPart')['Surface'].value_counts()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"**Conclusions**\n* Ankle injuries are more happening on the synthetic turf than natural one's.\n* Knees injuries are the same in both the turfs.\n* Toes injuries are 5* more in the synthetic field than the natural one."},{"metadata":{"_kg_hide-input":true,"_kg_hide-output":true,"trusted":true},"cell_type":"code","source":"df = Injury_games_play.groupby('BodyPart')['Surface'].value_counts().unstack().reset_index()\ndf","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"**Let's visualize our findings in a graph image**"},{"metadata":{"_kg_hide-output":false,"trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"df['Natural'] = df['Natural'].fillna(0)\ndf['Synthetic'] = df['Synthetic'].fillna(0)\n\nfig = go.Figure(data=[\n    go.Bar(x=df.BodyPart, y=df.Natural,text='y',hovertext='Natural'),\n    go.Bar(x=df.BodyPart, y=df.Synthetic,text='y',hovertext='Synthetic')\n])\n# Change the bar mode\nfig.update_layout(barmode='stack')\nfig.update_layout(height=500,width=800, title=\" All Body Part injury due to Turfs\",xaxis_title='Turfs',yaxis_title='Injuries',title_x=0.5,showlegend=False)\nfig.show()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Deep understanding of Injuries and it's relation to different factors"},{"metadata":{},"cell_type":"markdown","source":"**What's kind of play which effects different Body parts on these two turfs?**"},{"metadata":{"trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"Injury_games_play.groupby(['BodyPart','PlayType'])['Surface'].value_counts()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"**Conclusions**\n* Ankle injuries are happening more on synthetic surface than natural(also cumulatively ~15%) during pass of the play.\n* Ankle injuries are happening as much on synthetic surface as natural(also cumulatively ~14%) during rush of the play.\n* Knees injuries are happening more on natural surface than synthetic(also cumulatively ~14%) during pass of the play.\n* Knees injuries are happening more on natural surface than synthetic(also cumulatively ~5%) during punt of the play.\n* Knees injuries are happening more on synthetic surface than natural(also cumulatively ~8%) during rush of the play."},{"metadata":{"trusted":true,"_kg_hide-input":true,"_kg_hide-output":true},"cell_type":"code","source":"df = Injury_games_play.groupby(['BodyPart','PlayType'])['Surface'].value_counts().unstack().reset_index()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_kg_hide-input":true,"_kg_hide-output":true},"cell_type":"code","source":"df.head()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"**Putting the numbers into the visualization(Hover over for play information)**"},{"metadata":{"trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"df['Natural'] = df['Natural'].fillna(0)\ndf['Synthetic'] = df['Synthetic'].fillna(0)\n\nfig = go.Figure(data=[\n    go.Bar(x=df.BodyPart, y=df.Natural,text='y',hovertext=df['PlayType'],name='Natural'),\n    go.Bar(x=df.BodyPart, y=df.Synthetic,text='y',hovertext=df['PlayType'],name='Synthetic')\n])\n# Change the bar mode\nfig.update_layout(barmode='stack')\nfig.update_layout(height=500,width=800, title=\" All Body Part injury due to Play in different Turfs\",xaxis_title='Body Parts',yaxis_title='Injuries',title_x=0.5,showlegend=False)\nfig.show()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"**Number of injuries in each play according to injured body parts on the Natural Turf**"},{"metadata":{"trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"df.groupby(['BodyPart','PlayType'])['Natural'].sum()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"**Number of injuries in each play according to injured body parts on the Synthetic Turf**"},{"metadata":{"trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"df.groupby(['BodyPart','PlayType'])['Synthetic'].sum()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"**Visualization of different play and body parts(on hover) involving injuries**"},{"metadata":{"trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"\n\nfig = go.Figure(data=[\n    go.Bar(x=df.PlayType, y=df.Synthetic,text='y',hovertext=df['BodyPart'],name='Synthetic'),\n    go.Bar(x=df.PlayType, y=df.Natural,text='y',hovertext=df['BodyPart'],name='Natural')\n])\n# Change the bar mode\nfig.update_layout(barmode='stack')\nfig.update_layout(height=600,width=800, title=\" All Body Part injury due to PlayType\",xaxis_title='Types of play',yaxis_title='Injuries',title_x=0.5,showlegend=False)\nfig.show()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"**How many days a player is missing due to different body parts getting injured on these two turfs?**"},{"metadata":{"trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"Injury_games_play.groupby(['BodyPart','DaysMissed'])['Surface'].value_counts()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"**Conclusions**\n* An ankle injury is leading to minor injury to major injuries involving 1+ day missing to 42+ days missing.\n* Almost two times a player is missing 42+ days due to ankle injury in the synthetic surface play over natural surface play.\n* Almost four times a player is missing 42+ days due to foot injury in the natural surface play over synthetic surface play.\n* Almost three times a player is missing 7+ days due to toes injury in the natural surface play over synthetic surface play.\n* Severe type of injuries are happening on Natural turf than Synthetic and injured parts are Ankle/Knees as expected but light injuries are happening over Synthetic turf more than a normal event."},{"metadata":{"trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"df = Injury_games_play.groupby(['BodyPart','DaysMissed'])['Surface'].value_counts().unstack().reset_index()\n","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"**Visualization of our findings (Hover over for injured body parts)**"},{"metadata":{"trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"\n\nfig = go.Figure(data=[\n    go.Bar(x=df.DaysMissed, y=df.Synthetic,text='y',hovertext=df['BodyPart'],name='Synthetic'),\n    go.Bar(x=df.DaysMissed, y=df.Natural,text='y',hovertext=df['BodyPart'],name='Natural')\n])\n# Change the bar mode\nfig.update_layout(barmode='stack')\nfig.update_layout(height=600,width=800, title=\" All Body Part injured for durations\",xaxis_title='No of absent days due to injuries ',yaxis_title='Injuries',title_x=0.5,showlegend=False)\nfig.show()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"**Number of injuries leading to missing days according to injured body parts over the Natural Turf**"},{"metadata":{"trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"df.groupby(['BodyPart','DaysMissed'])['Natural'].sum()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"**Number of injuries leading to missing days according to injured body parts over the Synthetic Turf**"},{"metadata":{"trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"df.groupby(['BodyPart','DaysMissed'])['Synthetic'].sum()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"**Which day of the year injuries are happening more than often ?**"},{"metadata":{"trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"Injury_games_play.groupby(['BodyPart','PlayerDay'])['Surface'].value_counts()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"**Conclusions**\n* An ankle injury is happening more than often during 8 to 15 days of the calendar play.\n* A knee injury is happening more than often during 15 to 30 days of the calendar play.\n* An ankle injury is happening more on Synthetic turf during early days of the season.\n* A knee injury is happening more on Natural turf during early days of the season."},{"metadata":{"trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"df = Injury_games_play.groupby(['BodyPart','PlayerDay'])['Surface'].value_counts().unstack().reset_index()\n","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"**Visualization of our findings (Hover over for body parts)**"},{"metadata":{"trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"df['Natural'] = df['Natural'].fillna(0)\ndf['Synthetic'] = df['Synthetic'].fillna(0)\n\nfig = make_subplots(\n    rows=1, cols=2,\n    subplot_titles=(\"Synthetic\",\"Natural\"))\n\nfig.add_trace(go.Bar(x=df.PlayerDay, y=df.Synthetic,text='y',hovertext=df['BodyPart'],name='Synthetic'),\n              row=1, col=1)\nfig.add_trace(go.Bar(x=df.PlayerDay, y=df.Natural,text='y',hovertext=df['BodyPart'],name='Natural'),\n              row=1, col=2)\n\n# Change the bar mode\nfig.update_xaxes(title_text=\"Player Day\", row=1, col=1)\nfig.update_xaxes(title_text=\"Player Day\",row=1, col=2)\nfig.update_yaxes(title_text=\"Injuries\", row=1, col=1)\nfig.update_yaxes(title_text=\"Injuries\",row=1, col=2)\nfig.update_layout(height=600,width=800, title=\" All Body Part injury depending on Players day of the year\",title_x=0.5,showlegend=False)\nfig.show()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"**Which game of the season bringing more injuries to different body parts due to these two surface?**"},{"metadata":{"trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"Injury_games_play.groupby(['BodyPart','PlayerGame'])['Surface'].value_counts()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"**Conclusions**\n* An ankle injury is happening more during first game to tenth game of the season. \n* A knee is happening more during first game to tenth game of the season.\n* An ankle injury during the early games are happening more on synthetic turf than the natural turf.\n* A knee injury during the early games are happening more on natural turf than the synthetic turf."},{"metadata":{"trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"df = Injury_games_play.groupby(['BodyPart','PlayerGame'])['Surface'].value_counts().unstack().reset_index()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"**Visualization of our findings (Hover over for body parts)**"},{"metadata":{"trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"df['Natural'] = df['Natural'].fillna(0)\ndf['Synthetic'] = df['Synthetic'].fillna(0)\n\nfig = make_subplots(\n    rows=1, cols=2,\n    subplot_titles=(\"Synthetic\",\"Natural\"))\n\nfig.add_trace(go.Bar(x=df.PlayerGame, y=df.Synthetic,text='y',hovertext=df['BodyPart'],name='Synthetic'),\n              row=1, col=1)\nfig.add_trace(go.Bar(x=df.PlayerGame, y=df.Natural,text='y',hovertext=df['BodyPart'],name='Natural'),\n              row=1, col=2)\n# Change the bar mode\nfig.update_xaxes(title_text=\"Player Game\", row=1, col=1)\nfig.update_xaxes(title_text=\"Player Game\",row=1, col=2)\nfig.update_yaxes(title_text=\"Injuries\", row=1, col=1)\nfig.update_yaxes(title_text=\"Injuries\",row=1, col=2)\nfig.update_layout(height=600,width=800, title=\" All Body Part injury depending on Players Game\",title_x=0.5,showlegend=False)\nfig.show()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"**Number of injuries on each game day according to injured body parts on the Natural turf**"},{"metadata":{"trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"df.groupby(['BodyPart','PlayerGame'])['Natural'].sum()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"**Number of injuries on each game day according to injured body parts on the Synthetic turf**"},{"metadata":{"trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"df.groupby(['BodyPart','PlayerGame'])['Synthetic'].sum()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"**What are the injured player's position according to injured body parts on these two surface?**"},{"metadata":{"trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"Injury_games_play.groupby(['BodyPart','RosterPosition'])['Surface'].value_counts()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"**Conclusions**\n* Five cornerbacks have suffered from ankle injury on Synthetic surface.\n* Linebacker, Safety and wide receivers have suffered almost same number of ankle injuries over Natural or synthetic surface.\n* Foot injury for all player's positon are same over the two surface.\n* Three runningbacks have suffered from knee injury on Synthetic surface which is three times more than Natural surface.\n* Linebackers suffer from knee injury mostly no matter what surface it's."},{"metadata":{"trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"df = Injury_games_play.groupby(['BodyPart','RosterPosition'])['Surface'].value_counts().unstack().reset_index()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"**Visualization of our findings (Hover over for body parts)**"},{"metadata":{"trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"\n\nfig = go.Figure(data=[\n    go.Bar(x=df.RosterPosition, y=df.Synthetic,text='y',hovertext=df['BodyPart'],name='Synthetic'),\n    go.Bar(x=df.RosterPosition, y=df.Natural,text='y',hovertext=df['BodyPart'],name='Natural')\n])\n# Change the bar mode\nfig.update_layout(barmode='stack')\nfig.update_layout(height=600,width=800, title=\" All Body Part injured according to Injured Player Positions\",xaxis_title='Injured Player Position',yaxis_title='Injuries',title_x=0.5,showlegend=False)\nfig.show()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"**Number of injuries a player is facing while playing in that position on the Natural turf**"},{"metadata":{"trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"df.groupby(['BodyPart','RosterPosition'])['Natural'].sum()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"**Number of injuries a player is facing while playing in that position on the Synthetic turf**"},{"metadata":{"trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"df.groupby(['BodyPart','RosterPosition'])['Synthetic'].sum()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"**What are the involving players positions according to injured body parts over thes two surface?**"},{"metadata":{"trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"Injury_games_play.groupby(['BodyPart','Position'])['Surface'].value_counts()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"**Conclusions**\n* A centerback position player has been involved in 5 ankle injuries on Synthetic surface.\n* An outside linebacker and wide receiver position players are involved almost similar number of times on Natural or synthetic turf, also cumulatively they cover up ~16% of the ankle/knees injuries.\n* A running back position was involved in knee injury 3 times more on the synthetic surface than natural surface.\n* An outside linebacker position player has been involved in knee injury 2 times more on the natural surface than synthetic surface."},{"metadata":{"trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"df = Injury_games_play.groupby(['BodyPart','Position'])['Surface'].value_counts().unstack().reset_index()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"**Visualiztion of our findings (Hover over for body parts)**"},{"metadata":{"trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"\n\nfig = go.Figure(data=[\n    go.Bar(x=df.Position, y=df.Synthetic,text='y',hovertext=df['BodyPart'],name='Synthetic'),\n    go.Bar(x=df.Position, y=df.Natural,text='y',hovertext=df['BodyPart'],name='Natural')\n])\n# Change the bar mode\nfig.update_layout(barmode='stack')\nfig.update_layout(height=600,width=800, title=\" All Body Part injured due to Involving Player Position\",xaxis_title='Involving Players Position',yaxis_title='Injuries',title_x=0.5,showlegend=False)\nfig.show()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"**Number of injuries involving the player's position according to injured body parts on Natural Turf**"},{"metadata":{"trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"df.groupby(['BodyPart','Position'])['Natural'].sum()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"**Number of injuries involving the player's position according to injured body parts on Synthetic Turf**"},{"metadata":{"trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"df.groupby(['BodyPart','Position'])['Synthetic'].sum()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"**What was the weather when the injuries happened to specific body parts on these two surface?**"},{"metadata":{"trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"Injury_games_play.groupby(['BodyPart','Weather'])['Surface'].value_counts()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"**Conclusions**\n* A cloudy weather leads to twice more ankle injury on synthetic surface than natural surface.\n* An indoor weather leads to almost 8% ankle/knee injuries of the total injury.\n* A sunny weather happens to be involved in 5 natural turf knee injuries which is 5 times of synthetic turf maybe it was some dangerous play but this ratio do raise some eyebrows."},{"metadata":{"trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"df = Injury_games_play.groupby(['BodyPart','Weather'])['Surface'].value_counts().unstack().reset_index()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"**Visualiztion of our findings (Hover over for body parts)**"},{"metadata":{"trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"\n\nfig = go.Figure(data=[\n    go.Bar(x=df.Weather, y=df.Synthetic,text='y',hovertext=df['BodyPart'],name='Synthetic'),\n    go.Bar(x=df.Weather, y=df.Natural,text='y',hovertext=df['BodyPart'],name='Natural')\n])\n# Change the bar mode\nfig.update_layout(barmode='stack')\nfig.update_layout(height=600,width=800, title=\" All Body Part injured due to weather\",xaxis_title='Weather',yaxis_title='Injuries',title_x=0.5,showlegend=False)\nfig.show()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"**Number of injuries in different weather according to injured body parts on the Natural Turf**"},{"metadata":{"trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"df.groupby(['BodyPart','Weather'])['Natural'].sum()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"**Number of injuries in different weather according to injured body parts on the Synthetic Turf**"},{"metadata":{"trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"df.groupby(['BodyPart','Weather'])['Synthetic'].sum()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"**What were the stadium types which caused more damage to different body parts on these two turfs?**"},{"metadata":{"trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"Injury_games_play.groupby(['BodyPart','StadiumType'])['Surface'].value_counts()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"**Conclusions**\n* A synthetic turf inside indoor stadium caused almost ~25% of the total ankle and knees injuries.\n* A natural turf inside outdoor stadium caused almost ~28% of the total ankle and knees injuries.\n* In outdoor stadium there's more chance of players getting injured on natural turf than synthetic one. "},{"metadata":{"trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"df = Injury_games_play.groupby(['BodyPart','StadiumType'])['Surface'].value_counts().unstack().reset_index()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"**Visualization of our findings (Hover over for body part info)**"},{"metadata":{"trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"\n\nfig = go.Figure(data=[\n    go.Bar(x=df.StadiumType, y=df.Synthetic,text='y',hovertext=df['BodyPart'],name='Synthetic'),\n    go.Bar(x=df.StadiumType, y=df.Natural,text='y',hovertext=df['BodyPart'],name='Natural')\n])\n# Change the bar mode\nfig.update_layout(barmode='stack')\nfig.update_layout(height=600,width=800, title=\" All Body Part injured due to different Stadium Types\",xaxis_title='Stadium Types',yaxis_title='Injuries',title_x=0.5,showlegend=False)\nfig.show()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"**Number of injuries according to body parts on the natural turf**"},{"metadata":{"trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"df.groupby(['BodyPart','StadiumType'])['Natural'].sum()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"**Number of injuries according to body parts on the synthetic turf**"},{"metadata":{"trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"df.groupby(['BodyPart','StadiumType'])['Synthetic'].sum()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"**What kind of play has lead to severe kind of injury depending on number of days missed over these two turfs?**"},{"metadata":{"trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"Injury_games_play.groupby(['BodyPart','PlayType','DaysMissed'])['Surface'].value_counts()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"**Conclusions**\n* Most severe ankle injuries(42+) has happened during pass play on Synthetic turf.\n* Most severe knee injuries(42+) has happened more during rush/punt play on Synthetic turf than natural turf.\n* Light injuries (1+/7+) in any body parts are equal over the two surfaces.\n* Foot injuries are always severe(28+ or 42+) no matter what the surface has been.\n"},{"metadata":{"trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"df = Injury_games_play.groupby(['BodyPart','PlayType','DaysMissed'])['Surface'].value_counts().unstack().reset_index()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"**Visualization of our findings (Hover for more info)**"},{"metadata":{"trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"df['Natural'] = df['Natural'].fillna(0)\ndf['Synthetic'] = df['Synthetic'].fillna(0)\n\nfig = make_subplots(\n    rows=2, cols=2,\n    subplot_titles=(\"Synthetic\",\"Natural\",\"Natural\",\"Synthetic\"))\n\nfig.add_trace(go.Bar(x=df.PlayType, y=df.Synthetic,text='y',hovertext=df['BodyPart'],name='Synthetic'),\n              row=1, col=1)\nfig.add_trace(go.Bar(x=df.PlayType, y=df.Natural,text='y',hovertext=df['BodyPart'],name='Natural'),\n              row=2, col=1)\nfig.add_trace(go.Bar(x=df.DaysMissed, y=df.Synthetic,text='y',hovertext=df['BodyPart'],name='Synthetic'),\n              row=2, col=2)\nfig.add_trace(go.Bar(x=df.DaysMissed, y=df.Natural,text='y',hovertext=df['BodyPart'],name='Natural'),\n              row=1, col=2)\n# Change the bar mode\n# Update xaxis properties\nfig.update_xaxes(title_text=\"PlayType\", row=1, col=1)\nfig.update_xaxes(title_text=\"DaysMissed\",row=1, col=2)\nfig.update_xaxes(title_text=\"PlayType\", showgrid=False, row=2, col=1)\nfig.update_xaxes(title_text=\"DaysMissed\", row=2, col=2)\n\n# Update yaxis properties\nfig.update_yaxes(title_text=\"Injuries\", row=1, col=1)\nfig.update_yaxes(title_text=\"Injuries\", row=1, col=2)\nfig.update_yaxes(title_text=\"Injuries\", showgrid=False, row=2, col=1)\nfig.update_yaxes(title_text=\"Injuries\", row=2, col=2)\nfig.update_layout(height=600,width=800, title=\" All Body Part injury due to PlayType and DaysMissed\",title_x=0.5,showlegend=False)\nfig.show()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"**Number of injuries by play type and days missed due to injury on Natural turf**"},{"metadata":{"trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"df.groupby(['BodyPart','PlayType','DaysMissed'])['Natural'].sum()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"**Number of injuries by play type and days missed due to injury on Synthetic turf**"},{"metadata":{"trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"df.groupby(['BodyPart','PlayType','DaysMissed'])['Synthetic'].sum()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"**How may days a player is missing while playing in a specific position during the type of play and which body part is getting injured?**"},{"metadata":{"trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"Injury_games_play.groupby(['BodyPart','PlayType','RosterPosition','DaysMissed'])['Surface'].value_counts()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"**Conclusions**\n* Two players while playing pass in Safety position have suffered severe ankle injuries(42+) on synthetic surface.\n* Foot injuries were of severe type for lineman offense or defense during pass play on natural turf perhaps it was due to the play and nothing to do with turfs.\n* As expected Punt play brought some severe injury on both turfs for receivers and linebackers."},{"metadata":{"trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"df = Injury_games_play.groupby(['BodyPart','PlayType','RosterPosition','DaysMissed'])['Surface'].value_counts().unstack().reset_index()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"**Visualization of our findings (Hover for more info)**"},{"metadata":{"trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"df['Natural'] = df['Natural'].fillna(0)\ndf['Synthetic'] = df['Synthetic'].fillna(0)\n\nfig = make_subplots(\n    rows=3, cols=2,\n    subplot_titles=(\"Synthetic\",\"Natural\",\"Synthetic\",\"Natural\",\"Synthetic\",\"Natural\"))\n\nfig.add_trace(go.Bar(x=df.PlayType, y=df.Synthetic,text='y',hovertext=df['BodyPart'],name='Synthetic'),\n              row=1, col=1)\nfig.add_trace(go.Bar(x=df.RosterPosition, y=df.Synthetic,text='y',hovertext=df['BodyPart'],name='Synthetic'),\n              row=2, col=1)\nfig.add_trace(go.Bar(x=df.DaysMissed, y=df.Synthetic,text='y',hovertext=df['BodyPart'],name='Synthetic'),\n              row=3, col=1)\nfig.add_trace(go.Bar(x=df.PlayType, y=df.Natural,text='y',hovertext=df['BodyPart'],name='Natural'),\n              row=1, col=2)\nfig.add_trace(go.Bar(x=df.RosterPosition, y=df.Natural,text='y',hovertext=df['BodyPart'],name='Natural'),\n              row=2, col=2)\nfig.add_trace(go.Bar(x=df.DaysMissed, y=df.Natural,text='y',hovertext=df['BodyPart'],name='Natural'),\n              row=3, col=2)\n# Change the bar mode\n# Update xaxis properties\nfig.update_xaxes(title_text=\"PlayType\", row=1, col=1)\nfig.update_xaxes(title_text=\"PlayType\",row=1, col=2)\nfig.update_xaxes(title_text=\"RosterPosition\", showgrid=False, row=2, col=1)\nfig.update_xaxes(title_text=\"RosterPosition\", row=2, col=2)\nfig.update_xaxes(title_text=\"DaysMissed\", showgrid=False, row=3, col=1)\nfig.update_xaxes(title_text=\"DaysMissed\", row=3, col=2)\n\n# Update yaxis properties\nfig.update_yaxes(title_text=\"Injuries\", row=1, col=1)\nfig.update_yaxes(title_text=\"Injuries\", row=1, col=2)\nfig.update_yaxes(title_text=\"Injuries\", showgrid=False, row=2, col=1)\nfig.update_yaxes(title_text=\"Injuries\", row=2, col=2)\nfig.update_yaxes(title_text=\"Injuries\", showgrid=False, row=3, col=1)\nfig.update_yaxes(title_text=\"Injuries\", row=3, col=2)\nfig.update_layout(height=1000,width=800, title=\" All Body Part injury due to PlayType, Rosterposition and DaysMissed\",title_x=0.5,showlegend=False)\nfig.show()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"**Which body parts got injured most according to Play Type, player position and days missed on the Natural vs Synthetic turfs?\n**"},{"metadata":{"trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"Injury_games_play.groupby(['BodyPart','PlayType','Position','DaysMissed'])['Surface'].value_counts()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"**Conclusions**\n* The safeties are defensive backs who line up from ten to fifteen yards from the line of scrimmage. There are two variations of the position in a typical American formation: the free safety (FS) and the strong safety (SS) and they are involved in serious types of injury on Synthetic surface.\n* The outside linebacker (OLB), sometimes called the \"Buck, Sam, and Rebel\" is usually responsible for outside containment. This includes the strongside and weakside designations below. They are also responsible for blitzing the quarterback have suffered serious injury on synthetic surface due to rushing which is not a surprise.\n* Running backs have suffered mild injury on synthetic surface during pass play.\n"},{"metadata":{"trusted":true,"_kg_hide-input":true,"_kg_hide-output":true},"cell_type":"code","source":"df = Injury_games_play.groupby(['BodyPart','PlayType','Position','DaysMissed'])['Surface'].value_counts().unstack().reset_index()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"**Visualization of our findings (Hover for more info)**"},{"metadata":{"trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"df['Natural'] = df['Natural'].fillna(0)\ndf['Synthetic'] = df['Synthetic'].fillna(0)\n\nfig = make_subplots(\n    rows=3, cols=2,\n    subplot_titles=(\"Synthetic\",\"Natural\",\"Synthetic\",\"Natural\",\"Synthetic\",\"Natural\"))\n\nfig.add_trace(go.Bar(x=df.PlayType, y=df.Synthetic,text='y',hovertext=df['BodyPart'],name='Synthetic'),\n              row=1, col=1)\nfig.add_trace(go.Bar(x=df.Position, y=df.Synthetic,text='y',hovertext=df['BodyPart'],name='Synthetic'),\n              row=2, col=1)\nfig.add_trace(go.Bar(x=df.DaysMissed, y=df.Synthetic,text='y',hovertext=df['BodyPart'],name='Synthetic'),\n              row=3, col=1)\nfig.add_trace(go.Bar(x=df.PlayType, y=df.Natural,text='y',hovertext=df['BodyPart'],name='Natural'),\n              row=1, col=2)\nfig.add_trace(go.Bar(x=df.Position, y=df.Natural,text='y',hovertext=df['BodyPart'],name='Natural'),\n              row=2, col=2)\nfig.add_trace(go.Bar(x=df.DaysMissed, y=df.Natural,text='y',hovertext=df['BodyPart'],name='Natural'),\n              row=3, col=2)\n# Change the bar mode\n# Update xaxis properties\nfig.update_xaxes(title_text=\"PlayType\", row=1, col=1)\nfig.update_xaxes(title_text=\"PlayType\",row=1, col=2)\nfig.update_xaxes(title_text=\"Position\", showgrid=False, row=2, col=1)\nfig.update_xaxes(title_text=\"Position\", row=2, col=2)\nfig.update_xaxes(title_text=\"DaysMissed\", showgrid=False, row=3, col=1)\nfig.update_xaxes(title_text=\"DaysMissed\", row=3, col=2)\n\n# Update yaxis properties\nfig.update_yaxes(title_text=\"Injuries\", row=1, col=1)\nfig.update_yaxes(title_text=\"Injuries\", row=1, col=2)\nfig.update_yaxes(title_text=\"Injuries\", showgrid=False, row=2, col=1)\nfig.update_yaxes(title_text=\"Injuries\", row=2, col=2)\nfig.update_yaxes(title_text=\"Injuries\", showgrid=False, row=3, col=1)\nfig.update_yaxes(title_text=\"Injuries\", row=3, col=2)\nfig.update_layout(height=1000,width=800, title=\" All Body Part injury due to PlayType, Position and DaysMissed\",title_x=0.5,showlegend=False)\nfig.show()","execution_count":null,"outputs":[]},{"metadata":{"_kg_hide-output":true,"trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"def preprocess_samp_play(samp_play):\n\n    play_df = PlayerTrackData[PlayerTrackData.PlayKey==samp_play]\n    df = play_df.iloc[np.flatnonzero((play_df.event == 'ball_snap') | (play_df.event == 'kickoff'))[0]:]\n    df['event'].ffill(inplace=True)\n\n    # Calculate instantaneous acceleration\n    df['a'] = (df.s - df.s.shift(1)) / (df.time - df.time.shift(1))\n    df.a.iloc[0] = 0 # At the moment of ball_snap or kickoff, acceleration is likely 0\n    \n    return df","execution_count":null,"outputs":[]},{"metadata":{"_kg_hide-input":true,"trusted":true},"cell_type":"code","source":"def plot_injury_play(samp_play, df):\n\n    # Define the basic figure consisting in 6 traces: two in the field subplot,\n    # 2 in the speed subplot, and 2 in the accel subplot. These will be updated\n    # by frames:\n\n    x = df.x.values\n    y = df.y.values\n    N = df.shape[0] - 1\n    title_string = (samp_play+', '+\n                   InjuryRecord[InjuryRecord.PlayKey==samp_play].BodyPart.values[0]+', '+\n                   'M1: '+str(InjuryRecord[InjuryRecord.PlayKey==samp_play].DM_M1.values[0])+', '+\n                   'M7: '+str(InjuryRecord[InjuryRecord.PlayKey==samp_play].DM_M7.values[0])+', '+\n                   'M28: '+str(InjuryRecord[InjuryRecord.PlayKey==samp_play].DM_M28.values[0])+', '+\n                   'M42: '+str(InjuryRecord[InjuryRecord.PlayKey==samp_play].DM_M42.values[0])+', '+\n                   PlayList[PlayList.PlayKey==samp_play].RosterPosition.values[0]+', '+\n                   str(PlayList[PlayList.PlayKey==samp_play].StadiumType.values[0])+', '+\n                   PlayList[PlayList.PlayKey==samp_play].FieldType.values[0])\n\n    fig = dict(\n        layout = dict(height=400,\n            xaxis1 = {'domain': [0.0, 0.75], 'anchor': 'y1', 'range': [0, 120], 'tickmode': 'array',\n                      'tickvals': [0, 10, 35, 60, 85, 110, 120],\n                      'ticktext': ['End', 'G', '25', '50', '25', 'G', 'End']},\n            yaxis1 = {'domain': [0.0, 1], 'anchor': 'x1', 'range': [0, 160/3], \n                      'scaleanchor': 'x1', 'scaleratio': 1, 'tickmode': 'array',\n                      'tickvals': [0, 23.583, 29.75, 160/3],\n                      'ticktext': ['Side', 'Hash', 'Hash', 'Side']},\n            xaxis2 = {'domain': [0.8, 1], 'anchor': 'y2', 'range': [0, N]},\n            yaxis2 = {'domain': [0.0, 0.475], 'anchor': 'x2', 'range': [0, 10]},\n            xaxis3 = {'domain': [0.8, 1], 'anchor': 'y3', 'range': [0, N],\n                      'showticklabels': False},\n            yaxis3 = {'domain': [0.525, 1], 'anchor': 'x3', 'range': [-10, 10]},\n            title = {'text': title_string, 'y':0.92, 'x':0, 'xanchor': 'left', 'yanchor': 'top',\n                     'font': dict(size=12)},\n            annotations= [{\"x\": 0.9, \"y\": 0.425, \"font\": {\"size\": 12}, \"text\": \"Speed\",\n                           \"xref\": \"paper\", \"yref\": \"paper\", \"xanchor\": \"center\",\n                           \"yanchor\": \"bottom\", \"showarrow\": False},\n                          {\"x\": 0.9, \"y\": 0.95, \"font\": {\"size\": 12}, \"text\": \"Accel\",\n                           \"xref\": \"paper\", \"yref\": \"paper\", \"xanchor\": \"center\",\n                           \"yanchor\": \"bottom\", \"showarrow\": False}],\n            plot_bgcolor = 'rgba(181, 226, 141, 1)', # https://www.hexcolortool.com/#b5e28d\n            margin = {'t': 50, 'b': 50, 'l': 50, 'r': 50},\n        ),\n\n        data = [\n            {'type': 'scatter', # This trace is identified inside frames as trace 0\n             'name': 'f1', \n             'x': x, \n             'y': y, \n             'hoverinfo': 'name+text', \n             'marker': {'opacity': 1.0, 'symbol': 'circle', 'line': {'width': 0, 'color': 'rgba(50,50,50,0.8)'}},\n             'line': {'color': 'rgba(255,79,38,1.000000)'}, \n             'mode': 'lines', \n             'fillcolor': 'rgba(255,79,38,0.600000)', \n             'legendgroup': 'f1',\n             'showlegend': False, \n             'xaxis': 'x1', 'yaxis': 'y1'},\n            {'type': 'scatter', # This trace is identified inside frames as trace 1\n             'name': 'f12', \n             'x': [x[0]],\n             'y': [y[0]],\n             'mode': 'markers+text',\n             'text': df.event.iloc[0],\n             'textposition': 'middle left' if x[0] >= 60 else 'middle right', #'middle right',\n             'showlegend': False,\n             'marker': {'size': 10, 'color':'black'},\n             'xaxis': 'x1', 'yaxis': 'y1'},\n            {'type': 'scatter', # # This trace is identified inside frames as trace 2\n             'name': 'f2', \n             'x': list(range(N)), \n             'y': df.s, \n             'hoverinfo': 'name+text', \n             'marker': {'opacity': 1.0, 'symbol': 'circle', 'line': {'width': 0, 'color': 'rgba(50,50,50,0.8)'}},\n             'line': {'color': 'rgba(255,79,38,1.000000)'}, \n             'mode': 'lines', \n             'fillcolor': 'rgba(255,79,38,0.600000)', \n             'legendgroup': 'f2',\n             'showlegend': False, \n             'xaxis': 'x2', 'yaxis': 'y2'},\n            {'type': 'scatter', # This trace is identified inside frames as trace 3\n             'name': 'f22', \n             'x': [0],\n             'y': [df.s.iloc[0]],\n             'mode': 'markers',\n             'showlegend': False,\n             'marker': {'size': 7, 'color':'black'},\n             'xaxis': 'x2', 'yaxis': 'y2'},\n            {'type': 'scatter', # # This trace is identified inside frames as trace 4\n             'name': 'f3', \n             'x': list(range(N)), \n             'y': df.a, \n             'hoverinfo': 'name+text', \n             'marker': {'opacity': 1.0, 'symbol': 'circle', 'line': {'width': 0, 'color': 'rgba(50,50,50,0.8)'}},\n             'line': {'color': 'rgba(255,79,38,1.000000)'}, \n             'mode': 'lines', \n             'fillcolor': 'rgba(255,79,38,0.600000)', \n             'legendgroup': 'f2',\n             'showlegend': False, \n             'xaxis': 'x3', 'yaxis': 'y3'},\n            {'type': 'scatter', # This trace is identified inside frames as trace 5\n             'name': 'f33', \n             'x': [0],\n             'y': [df.a.iloc[0]],\n             'mode': 'markers',\n             'showlegend': False,\n             'marker': {'size': 7, 'color':'black'},\n             'xaxis': 'x3', 'yaxis': 'y3'},\n        ]\n\n\n    )\n\n\n    frames = [dict(name=k,\n                   data=[dict(x=x, y=y),\n                         dict(x=[x[k]], y=[y[k]], text=df.event.iloc[k]),\n                         dict(x=list(range(N)), y=df.s),\n                         dict(x=[k], y=[df.s.iloc[k]]),\n                         dict(x=list(range(N)), y=df.a),\n                         dict(x=[k], y=[df.a.iloc[k]]),\n                       ],\n                   traces=[0,1,2,3,4,5]) for k in range(N)]\n\n\n\n    updatemenus = [dict(type='buttons',\n                        buttons=[dict(label='Play',\n                                      method='animate',\n                                      args=[[f'{k}' for k in range(N)], \n                                             dict(frame=dict(duration=25, redraw=False), \n                                                  transition=dict(duration=0),\n                                                  easing='linear',\n                                                  fromcurrent=True,\n                                                  mode='immediate'\n                                                                     )]),\n                                 dict(label='Pause',\n                                      method='animate',\n                                      args=[[None],\n                                            dict(frame=dict(duration=0, redraw=False), \n                                                 transition=dict(duration=0),\n                                                 mode='immediate' )])],\n                        direction= 'left', \n                        pad=dict(r= 10, t=85), \n                        showactive =True, x= 0.1, y= 0, xanchor= 'right', yanchor= 'top')\n                ]\n\n\n\n    sliders = [{'yanchor': 'top',\n                'xanchor': 'left', \n                'currentvalue': {'font': {'size': 16}, 'prefix': 'Frame: ', 'visible': True, 'xanchor': 'right'},\n                'transition': {'duration': 25.0, 'easing': 'linear'},\n                'pad': {'b': 10, 't': 50}, \n                'len': 0.9, 'x': 0.1, 'y': 0, \n                'steps': [{'args': [[k], {'frame': {'duration': 25.0, 'easing': 'linear', 'redraw': False},\n                                          'transition': {'duration': 0, 'easing': 'linear'}}], \n                           'label': k, 'method': 'animate'} for k in range(N)       \n                        ]}]\n\n\n\n    fig.update(frames=frames),\n    fig['layout'].update(updatemenus=updatemenus,\n              sliders=sliders)\n\n\n\n    iplot(fig)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"df_syn = Injury_games_play[Injury_games_play[\"Surface\"] == \"Synthetic\"]\ndf_syn = df_syn[df_syn[\"BodyPart\"] == \"Ankle\"]\ndf_syn_list = df_syn['PlayKey'].tolist()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"samp_play = np.random.choice(InjuryRecord.PlayKey[~InjuryRecord.PlayKey.isna()])\ndataset = preprocess_samp_play(samp_play)","execution_count":null,"outputs":[]},{"metadata":{"_kg_hide-input":true,"trusted":true},"cell_type":"code","source":"# Calculate acceleration\nPlayerTrackData['a'] = (PlayerTrackData.s - PlayerTrackData.s.shift(1)) / (PlayerTrackData.time - PlayerTrackData.time.shift(1))\n\n# Calculate instantaneous jerk\nPlayerTrackData['j'] = (PlayerTrackData.a - PlayerTrackData.a.shift(1)) / (PlayerTrackData.time - PlayerTrackData.time.shift(1))\ndataset['j'] = (dataset.a - dataset.a.shift(1)) / (dataset.time - dataset.time.shift(1))","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Statistics Analysis of players position and movements"},{"metadata":{},"cell_type":"markdown","source":"**Injured vs Non injured player's speed on the field**"},{"metadata":{"trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"fig = go.Figure()\n\nfig.add_trace(go.Histogram(\n    x=PlayerTrackData['s'].sample(10000),\n    histnorm='percent',\n    name='Non Injured'\n))\n\nfig.add_trace(go.Histogram(\n    x=dataset['s'],\n    histnorm='percent',\n    name='Injured'\n))\n\n# The two histograms are drawn on top of another\nfig.update_layout(\n    barmode='stack',\n    title_text='Injured vs Non Injured Player Speed Frequency Distribution', # title of plot\n    xaxis_title_text='Speed of the player', # xaxis label\n    yaxis_title_text='Count', # yaxis label\n    title_x=0.5,\n)\nfig.show()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"**Conclusions**\n* Players around having 9 mph are having more injuries with respect to non injured players.\n* All other distribution is equally distributed and have no significant meaning related to injury factor."},{"metadata":{},"cell_type":"markdown","source":"**Angle facing of injured vs non injured players**"},{"metadata":{"trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"fig = go.Figure()\n\nfig.add_trace(go.Histogram(\n    x=PlayerTrackData['o'].sample(10000),\n    histnorm='percent',\n    name='Non Injured'\n))\n\nfig.add_trace(go.Histogram(\n    x=dataset['o'],\n    histnorm='percent',\n    name='Injured'\n))\n\n# The two histograms are drawn on top of another\nfig.update_layout(\n    barmode='stack',\n    title_text='Injured vs Non Injured Player Orientation Frequency Distribution', # title of plot\n    xaxis_title_text='Angle Facing', # xaxis label\n    yaxis_title_text='Count', # yaxis label\n    title_x=0.5,\n)\nfig.show()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"**Conclusions**\n* Players having angles facing on the pitch around 340 degrees have more injuries than 350 degrees.\n* All other angles are equally distributed between injured and non injured players."},{"metadata":{},"cell_type":"markdown","source":"**Acceleration of injured vs non injured players**"},{"metadata":{"_kg_hide-input":true,"trusted":true},"cell_type":"code","source":"fig = go.Figure()\n\nfig.add_trace(go.Histogram(\n    x=PlayerTrackData['a'].sample(10000),\n    histnorm='percent',\n    name='Non Injured'\n))\n\nfig.add_trace(go.Histogram(\n    x=dataset['a'],\n    histnorm='percent',\n    name='Injured'\n))\n\n# The two histograms are drawn on top of another\nfig.update_layout(\n    barmode='stack',\n    title_text='Injured vs Non Injured Player accelaration Frequency Distribution', # title of plot\n    xaxis_title_text='Acceleration of the player', # xaxis label\n    yaxis_title_text='Count', # yaxis label\n    title_x=0.5,\n)\nfig.show()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"**Conclusions**\n* The acceleration of the injured and non injured players have the almost same distribution.\n* Acceleration isn't a major factor when it comes down to injuries happening."},{"metadata":{},"cell_type":"markdown","source":"**Impulse is the amount of force applied over a period of time, with greater impulse resulting in a greater change in momentum of the struck object. Jerk is a measure of velocity, defined as the change in acceleration divided by the change in time.**\n\n\n**Histogram of Jerk percentage distribution of injured players vs non injured players**"},{"metadata":{"_kg_hide-input":true,"trusted":true},"cell_type":"code","source":"fig = go.Figure()\n\nfig.add_trace(go.Histogram(\n    x=PlayerTrackData['j'].sample(10000),\n    histnorm='percent',\n    name='Non Injured'\n))\n\nfig.add_trace(go.Histogram(\n    x=dataset['j'],\n    histnorm='percent',\n    name='Injured'\n))\n\n# The two histograms are drawn on top of another\nfig.update_layout(\n    barmode='stack',\n    title_text='Injured vs Non Injured Player jerk Frequency Distribution', # title of plot\n    xaxis_title_text='Jerk of the player movement', # xaxis label\n    yaxis_title_text='Count', # yaxis label\n    title_x=0.5,\n)\nfig.show()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"**Conclusions**\n* Most of the play had around zero jerk so does the play involving injuries have the same too, which doesn't relate to our problem.\n* Jerk of the injured players are as much as the non injured players.\n"},{"metadata":{},"cell_type":"markdown","source":"**Injured vs non injured Player's position along the long axis **"},{"metadata":{"trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"fig = go.Figure()\n\nfig.add_trace(go.Histogram(\n    x=PlayerTrackData['x'].sample(10000),\n    histnorm='percent',\n    name='Non Injured'\n))\n\nfig.add_trace(go.Histogram(\n    x=dataset['x'],\n    histnorm='percent',\n    name='Injured'\n))\n\n# The two histograms are drawn on top of another\nfig.update_layout(\n    barmode='stack',\n    title_text='Injured vs Non Injured Player X Position Frequency Distribution', # title of plot\n    xaxis_title_text='X Position of the player', # xaxis label\n    yaxis_title_text='Count', # yaxis label\n    title_x=0.5,\n)\nfig.show()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"**Conclusions**\n* Hot areas are around 20s and 80s yards where most of the injuries have occured however most of the play was made around this area so it do not specify the relationship between injuries and the yard line.\n* Turfs doesn't matter when it comes to the position of the player on the field as it mostly depends on the type of play."},{"metadata":{},"cell_type":"markdown","source":"**Injured vs non injured Player's position along the short axis **"},{"metadata":{"trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"fig = go.Figure()\n\nfig.add_trace(go.Histogram(\n    x=PlayerTrackData['y'].sample(10000),\n    histnorm='percent',\n    name='Non Injured'\n))\n\nfig.add_trace(go.Histogram(\n    x=dataset['y'],\n    histnorm='percent',\n    name='Injured'\n))\n\n# The two histograms are drawn on top of another\nfig.update_layout(\n    barmode='stack',\n    title_text='Injured vs Non Injured Player Y Position Frequency Distribution', # title of plot\n    xaxis_title_text='Y position of the player', # xaxis label\n    yaxis_title_text='Count', # yaxis label\n    title_x=0.5,\n)\nfig.show()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"**Conclusions**\n* Almost all of these injuries have happened at the tight end of the field.\n* It doesn't specify why all those injuries happened there but the hot areas are the tight end where most of the injuries happened regardless of the turf. "},{"metadata":{},"cell_type":"markdown","source":"**Although i don't believe temperature play any kind of significant role in injuries but let's find out the distribution of temperature injured play vs non injury plays**"},{"metadata":{"trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"fig = go.Figure()\n\nfig.add_trace(go.Box(\n    x=Injury_games_play['Temperature'],\n    name='Injured play Temperature'\n))\n\nfig.add_trace(go.Box(\n    x=PlayList['Temperature'],\n    name='Non Injured play Temperature'\n))\n\n# The two histograms are drawn on top of another\nfig.update_layout(\n    title_text='Injured vs Non Injured Player Temperature Distribution', # title of plot\n    xaxis_title_text='Temperature', # xaxis label\n    title_x=0.5,\n)\nfig.update_xaxes(range=[0, 110])\nfig.show()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"**As i thought there wasn't any kind of significance difference between injury play and non injury play, it would have been on warmer side in injury play but there's not any significant difference.**"},{"metadata":{},"cell_type":"markdown","source":"# Plotting the Play and visualize the happening"},{"metadata":{},"cell_type":"markdown","source":"**Player's movement and speed during the injured play**"},{"metadata":{"trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"print(\"Acceleration of player is\" +\" \"+ str(dataset['a'].values[0]) + \"  \" + \"Speed of player is\" + \" \"+ str(dataset['s'].values[0]) )\nexample_play_id = dataset['PlayKey'].values[0]\nfig, ax = create_football_field()\nPlayerTrackData.query('PlayKey == @example_play_id').plot(kind='scatter', x='x', y='y', ax=ax, color='orange')\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"**Let's visualize the same play in an animation graph with speed and acceleration**"},{"metadata":{"trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"\nplot_injury_play(samp_play, dataset)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"**It clearly shows how the injury happened in a sample play with the sudden shift in acceleration and speed were high for the collision as per most of the cases.**"},{"metadata":{},"cell_type":"markdown","source":"# Conclusions\n"},{"metadata":{},"cell_type":"markdown","source":"**Major points to notice**\n* The early days are where most of the injuries have happened although synthetic surface has more injuries in the early days of the season.\n* It's the outside Linebackers and wide receivers which have suffered severe ankle injuries on synthetic surface than natural.\n* Pass and Rush play were mostly involved in the severe injuries, also the players which involves in it were Centerbacks who plays in Strong safety positions.\n* Toes injuries are happening on Synthetic surface than natural surface.\n* Cornerbacks are most exposed to ankle injuries on synthetic surface.\n* Injuries have more ratio than to all play data when players are facing ~350 degrees.\n* Foot injuries were the most severe on synthetic surface as they kept players out for 28+ days out at least.\n* Tight end collisons were most exposed to the ankle and knee injuries.\n* Punt blocker and wide receivers were at high risks during punt play for long time injuries."},{"metadata":{},"cell_type":"markdown","source":"# Precautions\n**More safety pads for ankle regions when players are playing on synthetic surface.**\n\n**More safety pads for Outside linebackers and wide receivers when they are playing on synthetic surface.**\n\n**Don't play players who are exposed to injuries in the early days.**\n\n**Keep an eye out for Blindside block(~350 degrees) as they happens to be major reason for concussions.**\n\n**Synthetic surface happens to be involved in all kind of play type injuries especially for long time injuries when the weather is cloudy, so need to improvise on that part. Making more suitable for cloudy or rainy weather.**\n\n"},{"metadata":{},"cell_type":"markdown","source":"# References\n\n**Football field layout - https://www.kaggle.com/robikscube/nfl-1st-and-future-analytics-intro**\n\n**Animation Play - https://www.kaggle.com/bgpablo/visualization-of-player-movement-speed-accel**\n\n**Wikipedia - https://en.wikipedia.org/wiki/National_Football_League**\n\n**NFL Website - http://www.nfl.com/**\n\n**Understanding - https://www.dummies.com/sports/football/offense/footballs-offensive-team-the-receivers/**"}],"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}