{"cells":[{"metadata":{},"cell_type":"markdown","source":"# NFL 1st and Future 2019\n\ntl;dr:\n\n**In this challenge, you're 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\nSubmissions will be judged by the NFL based on how well they address:\n- Representation of player movement, including, but not limited to, the development of novel metrics that characterize player movement on the field:\n- Identification of specific variables that present an elevated risk of injury:\n- Evaluation of differences in player movement between playing surfaces:\n\nSubmissions will be scored using the following rubric:\n- Creativity and Presentation (5 points)\n- Methodology (5 points)\n- Application (5 points)"},{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"import numpy as np\nimport pandas as pd\nimport matplotlib.pylab as plt\nimport seaborn as sns\nimport matplotlib.patches as patches\nsns.set_style(\"whitegrid\")","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Data:\nThere are three files provided in the dataset, as described below:\n\n1. **Injury 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\n2. **Play 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\n3. **Player 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).\n\n"},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"playlist = pd.read_csv('../input/nfl-playing-surface-analytics/PlayList.csv')\ninj = pd.read_csv('../input/nfl-playing-surface-analytics/InjuryRecord.csv')\ntrk = pd.read_csv('../input/nfl-playing-surface-analytics/PlayerTrackData.csv')","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Injury Data\n- PlayerKey, GameId, PlayKey\n- BodyPart\n- Surface\n- DM_M1, DM_M7, DM_28, DM_42 - One hot encoding the number of days missed for injury"},{"metadata":{"trusted":true},"cell_type":"code","source":"inj.groupby('BodyPart').count()['PlayerKey'] \\\n    .sort_values() \\\n    .plot(kind='bar', figsize=(15, 5), title='Count of injuries by Body Part')\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"inj.groupby('Surface').count()['PlayerKey'] \\\n    .sort_values() \\\n    .plot(kind='bar', figsize=(15, 5), title='Count of injuries by Body Part')\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"inj_detailed.groupby('PlayType').count()['DM_M42'] \\\n    .sort_values() \\\n    .plot(figsize=(15, 5), kind='bar', title='Days missed by PlayType')\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Playlist Data"},{"metadata":{"trusted":true},"cell_type":"code","source":"# Number of unique plays in the playlist dataset\nplaylist['PlayKey'].nunique()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"playlist[['PlayKey','PlayType']].drop_duplicates() \\\n    .groupby('PlayType').count()['PlayKey'] \\\n    .sort_values() \\\n    .plot(kind='barh',\n         figsize=(12, 6),\n          color='black',\n         title='Number of plays provided by type')\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Match Player info with injury data\n- Only 77 link up the player info"},{"metadata":{"trusted":true},"cell_type":"code","source":"inj_detailed = inj.merge(playlist)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"inj_detailed.groupby('RosterPosition').count()['PlayerKey'] \\\n    .sort_values() \\\n    .plot(figsize=(15, 5), kind='bar', title='Injured Players by Position')\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"inj_detailed.groupby('PlayType').count()['BodyPart'] \\\n    .sort_values() \\\n    .plot(figsize=(15, 5), kind='bar', title='Injured Players by BodyPart')\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"inj_detailed.groupby('PlayType').count()['PlayerKey'] \\\n    .sort_values() \\\n    .plot(figsize=(15, 5), kind='bar', title='Injured Players by PlayType')\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Plotting Plays\nCheck out my kernel here where I provide a function for creating and plotting a NFL football field.\n\nhttps://www.kaggle.com/robikscube/nfl-big-data-bowl-plotting-player-position"},{"metadata":{"_kg_hide-input":true,"trusted":true},"cell_type":"code","source":"def 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},"cell_type":"code","source":"example_play_id = inj['PlayKey'].values[0]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"trk.shape","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Plot path of injured player"},{"metadata":{"trusted":true},"cell_type":"code","source":"fig, ax = create_football_field()\ntrk.query('PlayKey == @example_play_id').plot(kind='scatter', x='x', y='y', ax=ax, color='orange')\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"inj_play_list = inj['PlayKey'].tolist()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Plotting every route of injured players\n- Too much info to draw conclusions, but fun to plot for context."},{"metadata":{"trusted":true},"cell_type":"code","source":"# Loop through all 99 inj plays\nfig, ax = create_football_field()\nfor playkey, inj_play in trk.query('PlayKey in @inj_play_list').groupby('PlayKey'):\n    inj_play.plot(kind='scatter', x='x', y='y', ax=ax, color='orange', alpha=0.2)\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Plotting routes of some non-injured players"},{"metadata":{"trusted":true},"cell_type":"code","source":"trk['PlayKey'].nunique()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"trk.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Loop through all 99 inj plays\nfig, ax = create_football_field()\nfor playkey, inj_play in trk.query('PlayKey not in @inj_play_list').head(50000).groupby('PlayKey'):\n    inj_play.plot(kind='scatter', x='x', y='y', ax=ax, color='red', alpha=0.2)\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Look at the top of each data file"},{"metadata":{"trusted":true},"cell_type":"code","source":"inj.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"trk.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"playlist.head()","execution_count":null,"outputs":[]},{"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}