{"cells":[{"metadata":{},"cell_type":"markdown","source":"![](http://www.google.com/url?sa=i&source=images&cd=&ved=2ahUKEwim7I3IzeDmAhVtmuAKHd_OAKkQjRx6BAgBEAQ&url=https%3A%2F%2Fwww.cnbc.com%2F2019%2F12%2F30%2Fnfl-ratings-recovering-new-media-deals-could-be-on-the-2020-agenda.html&psig=AOvVaw3exy8gLUZLNp789PHRSqAo&ust=1577906387273502)"},{"metadata":{},"cell_type":"markdown","source":"Football is one of the most popular sports worldwide. The frequency of football injuries is estimated to be approximately 10 to 35 per 1000 playing hours. The majority of injuries occur in the lower extremities, mainly in the knees and ankles. Considering the health and financial consequences of injury, an extensive data analysis to inspect the risk factors and reduce the incidence of injuries is urgently required. For this reason, an analysis of intrinsic (person-related) and extrinsic (environment-related) risk factors was undertaken based on a review of the datasets provided by NFL."},{"metadata":{},"cell_type":"markdown","source":"***Table of Contents***\n* 1.1 Import Libraries\n* 1.2 Read Data\n      Injuries Record\n      Play List\n      Player Track\n* 2.1 Characterize Movement\n      Metrics of Speed\n      Directional Change\n      Acceleration/Deceleration\n* 2.2 Identify Variables\n      Speed Analysis\n      Direction Analysis\n      Spatial Analysis\n* 2.3 Exploratory Data Analysis\n\n"},{"metadata":{"id":"ixLQUMKCa7xy","colab_type":"text"},"cell_type":"markdown","source":"**1.1 Import Libraries** "},{"metadata":{"id":"WH7F9ZOyakOU","colab_type":"code","colab":{},"trusted":true},"cell_type":"code","source":"import pandas as pd\nimport numpy as np\nimport math \nimport seaborn as sns\nimport matplotlib.pyplot as plt","execution_count":null,"outputs":[]},{"metadata":{"id":"dxl3X4a8a4Wi","colab_type":"text"},"cell_type":"markdown","source":"**1.2 Read Data**"},{"metadata":{"id":"x2Slxj6yZKFg","colab_type":"code","colab":{},"trusted":true},"cell_type":"code","source":"playlist = pd.read_csv('../input/nfl-playing-surface-analytics/PlayList.csv')\nplayertrack= pd.read_csv('../input/nfl-playing-surface-analytics/PlayerTrackData.csv')\ninjuries= pd.read_csv('../input/nfl-playing-surface-analytics/InjuryRecord.csv')","execution_count":null,"outputs":[]},{"metadata":{"id":"JwaG-9W5234M","colab_type":"text"},"cell_type":"markdown","source":"**Injuries Record**\n\nInformation about Injuries incurred. \nPlayerKey, GameID (PlayerKey-X), PlayKey (PlayerKey-GameID-X).\n\nBodyPart, Surface: character string\n\nDM: one-hot encoding indicating days missed.\n\n\n"},{"metadata":{"id":"nlMT_yTva2sW","colab_type":"code","colab":{"base_uri":"https://localhost:8080/","height":204},"outputId":"3ce2c4ea-6b5d-44c6-c25c-e2fe4a81fcd1","trusted":true},"cell_type":"code","source":"injuries.head()","execution_count":null,"outputs":[]},{"metadata":{"id":"TeC0sXKP2ZO6","colab_type":"text"},"cell_type":"markdown","source":"**Play List**"},{"metadata":{"id":"GRbIyb3_4IHs","colab_type":"text"},"cell_type":"markdown","source":"The play file contains information about each player-play in the dataset, to include the player’s assigned roster position, stadium type, field type, weather, play type, position for the play, and position group.\n\nPlayerDay: an integer sequence reflects timeline of a player's participation in games.\n\nPlayerGames: Identify player's games.\n\nPlayerGamePlay: running counts.\n"},{"metadata":{"id":"Fx8-fEQdbO-0","colab_type":"code","colab":{"base_uri":"https://localhost:8080/","height":394},"outputId":"3847d936-4b8c-4295-86c5-c0a1dd5a1b8a","trusted":true},"cell_type":"code","source":"playlist.head()","execution_count":null,"outputs":[]},{"metadata":{"id":"SivmJhXp5ZHg","colab_type":"text"},"cell_type":"markdown","source":"**Player Track**"},{"metadata":{"id":"sl5txGca5nfj","colab_type":"text"},"cell_type":"markdown","source":"The player track file in .csv format includes player position, direction, and orientation data for each player during the entire course of the play collected using the Next Gen Stats (NGS) system. This data is indexed by PlayKey (which includes information about the player and game), with the time variable providing a temporal index within an individual play.\n\nNote that the orientation variable should not be considered to be a reliable indicator of the actual direction a player is facing. The records for this study come from multiple seasons of the NFL during which different systems were used to calculate and record a player’s orientation. The orientation variable can be used to characterize how much a player is turning or pivoting during the course of a play. The “geography” of the direction variable does remain consistent across the study horizon."},{"metadata":{"id":"TghGDrZPbRs5","colab_type":"code","colab":{"base_uri":"https://localhost:8080/","height":204},"outputId":"b9532b9b-c2b1-4902-df49-316998bde4b4","trusted":true},"cell_type":"code","source":"playertrack.head()","execution_count":null,"outputs":[]},{"metadata":{"id":"3RiNcTjX7K4V","colab_type":"text"},"cell_type":"markdown","source":"**2.1 Characterize Movement**"},{"metadata":{"id":"uCEl5sO27h0b","colab_type":"text"},"cell_type":"markdown","source":"Representation of player movement, including, but not limited to, the development of novel metrics that characterize player movement on the field:\n\n*   Speed\n*   Directional changes\n*   Acceleration/Deceleration\n*   Distance\n\n\n\n"},{"metadata":{"id":"FWgYbJc77Izk","colab_type":"code","colab":{"base_uri":"https://localhost:8080/","height":187},"outputId":"c1af46ff-d54e-4659-87e1-375055aa0bda","trusted":true},"cell_type":"code","source":"playertrack.count()","execution_count":null,"outputs":[]},{"metadata":{"id":"cmTpx2uj9gIE","colab_type":"text"},"cell_type":"markdown","source":"**Metrics of Speed**\n\nWe want to redefine speed using Euclid Distance between two locations divided by time."},{"metadata":{"id":"wpmBsvOa-TCq","colab_type":"text"},"cell_type":"markdown","source":"How many PlayKeys are there?"},{"metadata":{"id":"iS2dDKeWcS8X","colab_type":"code","colab":{},"trusted":true},"cell_type":"code","source":"InjuryKeys = injuries['PlayKey'].unique()\nlen(injuries['PlayKey'].unique())\n\npt_filter = playertrack['PlayKey'].isin(InjuryKeys)\nplayertrack2 = playertrack[pt_filter]","execution_count":null,"outputs":[]},{"metadata":{"id":"Afn1kWZ_8Pfg","colab_type":"code","colab":{"base_uri":"https://localhost:8080/","height":34},"outputId":"838525dc-c248-4ab7-c36f-e1fdb7ec9b8d","trusted":true},"cell_type":"code","source":"PlayKeys = playertrack2['PlayKey'].unique()\nlen(playertrack2['PlayKey'].unique())","execution_count":null,"outputs":[]},{"metadata":{"id":"mcn3uZns-RxE","colab_type":"code","colab":{},"trusted":true},"cell_type":"code","source":"speed = []\n\nfor i in range(0,21904):\n      s = math.sqrt((round((playertrack2.iloc[i+1]['x'] - playertrack2.iloc[i]['x'])*100,3))**2 + (round((playertrack2.iloc[i+1]['y'] - playertrack2.iloc[i]['y'])*100,3))**2)\n      speed.append(s)\n    \nspeed.append(1000)\nspeed2 = speed\n\nfor i in range(0,21904):\n    if(( playertrack2.iloc[i]['PlayKey'] != playertrack2.iloc[i+1]['PlayKey'])):\n      speed2[i] = 1000\n\nplayertrack2['speed'] = speed2","execution_count":null,"outputs":[]},{"metadata":{"id":"LMKRftzsmRcT","colab_type":"text"},"cell_type":"markdown","source":"**Directional Changes**"},{"metadata":{},"cell_type":"markdown","source":"We redefine directional change for each PlayKey."},{"metadata":{"id":"p32KPyTHk4Tl","colab_type":"code","colab":{},"trusted":true},"cell_type":"code","source":"dc = []\n\nfor j in range(0,21904):\n      d = abs(playertrack2.iloc[j+1]['dir'] - playertrack2.iloc[j]['dir'])\n      dc.append(d)\n\ndc.append(1000)\n\nfor j in range(0,21904):\n    if(( playertrack2.iloc[j]['PlayKey'] != playertrack2.iloc[j+1]['PlayKey'])):\n      dc[j] = 1000\n    \nplayertrack2['dc'] = dc","execution_count":null,"outputs":[]},{"metadata":{"id":"PlirUIfKoM87","colab_type":"text"},"cell_type":"markdown","source":"**Acceleration/Deceleration**"},{"metadata":{},"cell_type":"markdown","source":"We redefine acceleration/deceleration using the speed variable we created."},{"metadata":{"id":"_wV-JoiqoMNw","colab_type":"code","colab":{},"trusted":true},"cell_type":"code","source":"ac = []\nfor k in range(0,21904):\n  a = playertrack2.iloc[k+1]['speed'] - playertrack2.iloc[k]['speed']\n  ac.append(a)\n\nac.append(1000)\n\nfor k in range(0,21904):\n    if(( playertrack2.iloc[k]['PlayKey'] != playertrack2.iloc[k+1]['PlayKey'])):\n      ac[k-1] = 1000\n      ac[k] = 1000\n        \nplayertrack2['ac'] = ac","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"playertrack2.head(10)","execution_count":null,"outputs":[]},{"metadata":{"id":"fl0dezmQZkYR","colab_type":"text"},"cell_type":"markdown","source":"**2.2 Identify Variables**\n\nIdentification of specific variables that present an elevated risk of injury:\n\n*   Are there specific movement patterns that correlate with the acute onset of injury (in general or by specific injury location)?\n*   Are there summary metrics of player movement which influence risk of injury?\n*   How do playing surface, game scenario, player movement, and weather interact to influence the risk of injury?"},{"metadata":{"id":"beNuUgUZZloJ","colab_type":"code","colab":{},"trusted":true},"cell_type":"code","source":"# Use seaborn style defaults and set the default figure size\nsns.set(rc={'figure.figsize':(16, 5)})","execution_count":null,"outputs":[]},{"metadata":{"id":"23E56lPrrfRx","colab_type":"code","colab":{},"trusted":true},"cell_type":"code","source":"pt_sp = playertrack2[playertrack2['speed']!=1000]","execution_count":null,"outputs":[]},{"metadata":{"id":"REEku0E5uzcH","colab_type":"code","colab":{"base_uri":"https://localhost:8080/","height":34},"outputId":"a6531c67-9e98-4987-b878-ae297995017f","trusted":true},"cell_type":"code","source":"# We take a look at the maximum time of game.\npt_sp['time'].max()","execution_count":null,"outputs":[]},{"metadata":{"id":"D2DXNKjd41Q9","colab_type":"text"},"cell_type":"markdown","source":"**Speed Analysis**"},{"metadata":{"id":"Nz2b4A2MuTq9","colab_type":"code","colab":{"base_uri":"https://localhost:8080/","height":372},"outputId":"8ef7503c-ce03-4b36-824a-8f4c41471022","trusted":true},"cell_type":"code","source":"ax = sns.lineplot(x=\"time\", y=\"speed\",\n             data=pt_sp)\nax.set_ylabel('Speed')\nax.set_xlabel('time')\nax.set_title(\"Lineplot of Speed by Time\")","execution_count":null,"outputs":[]},{"metadata":{"id":"hi4BVN5tycYl","colab_type":"text"},"cell_type":"markdown","source":"It is apparent that there are more acceleration/decceleration in the time range 50-70 minutes. Then we want to join other datasets to inspect risk factors such as ground surface and weather."},{"metadata":{"id":"PcrcnQtdxjqy","colab_type":"code","colab":{},"trusted":true},"cell_type":"code","source":"pt_sp2 = pd.merge(pt_sp, injuries, on = \"PlayKey\")","execution_count":null,"outputs":[]},{"metadata":{"id":"Fgf06-gV5Ran","colab_type":"code","colab":{},"trusted":true},"cell_type":"code","source":"pt_sp3 = pd.merge(pt_sp2, playlist, on = \"PlayKey\")","execution_count":null,"outputs":[]},{"metadata":{"id":"j11z2I8n5iZ4","colab_type":"code","colab":{"base_uri":"https://localhost:8080/","height":309},"outputId":"42a7591b-cf96-445c-c06e-28267e862617","trusted":true},"cell_type":"code","source":"pt_sp3.head()","execution_count":null,"outputs":[]},{"metadata":{"id":"7fyxKjmct4YD","colab_type":"code","colab":{"base_uri":"https://localhost:8080/","height":664},"outputId":"36bcf75e-d0bb-4d03-cf58-2497eaa974cb","trusted":true},"cell_type":"code","source":"fig, axes = plt.subplots(1, 1, figsize=(16, 10), sharex=True)\nax = sns.boxplot(data=pt_sp3, x='PlayKey', y='speed',\n            whis=\"range\", hue=\"Surface\",hue_order =[\"Natural\", \"Synthetic\"], dodge=False)\nax.set_ylabel('Speed')\nax.set_xlabel('Players')\nax.set_title(\"Boxplot of Speed for Injuried Players by Surface\")","execution_count":null,"outputs":[]},{"metadata":{"id":"UEB2P55v2BqE","colab_type":"code","colab":{"base_uri":"https://localhost:8080/","height":173},"outputId":"15c04245-c860-44d4-c41c-83bfaab9c18c","trusted":true},"cell_type":"code","source":"pt_sp2.groupby('Surface').agg({\"speed\":['mean','max','min','var']})","execution_count":null,"outputs":[]},{"metadata":{"id":"gwHs3Lvp46ej","colab_type":"text"},"cell_type":"markdown","source":"For all the injuried players, it seems that there is no significant speed difference with respect to surface. However, there is more variation in speed for synthetic surface."},{"metadata":{"id":"Moap01lu6SjX","colab_type":"code","colab":{},"trusted":true},"cell_type":"code","source":"w = []\n\nfor wea in pt_sp3['Weather']:\n  if (wea == \"Sunny\" or wea == \"Clear and warm\" or wea == \"Clear Skies\" or wea == \"Clear skies\" or wea == \"Mostly Sunny\"or wea == \"Mostly sunny\"or wea == \"Clear\"):\n    w.append(\"Sunny\")\n  elif(wea == \"Partly Cloudy\" or wea == \"Controlled Climate\" or wea == \"Cloudy\" or wea == \"Mostly cloudy\" or wea == \"Sun & clouds\" or wea == \"Coudy\" or wea == \"Cloudy and Cool\" ):\n    w.append(\"Cloudy\")\n  elif(wea == \"Rain\"or wea == \"Light Rain\"or wea == \"Rain shower\" or wea ==\"Cloudy with periods of rain, thunder possible. Winds shifting to WNW, 10-20 mph.\" or wea ==\"Fair\" or wea ==\"Cloudy, 50% change of rain\" ):\n    w.append(\"Rain\")\n  elif(wea == \"Indoors\"or wea ==\"Indoor\"):\n    w.append(\"Indoors\")\n  elif(wea == \"Cold\"):\n    w.append(\"Cold\")\n  else:\n    w.append(\"NA\")\n","execution_count":null,"outputs":[]},{"metadata":{"id":"7cCIrLpL8y5r","colab_type":"code","colab":{},"trusted":true},"cell_type":"code","source":"pt_sp3['wea'] = w","execution_count":null,"outputs":[]},{"metadata":{"id":"ppWjRPAM5rad","colab_type":"code","colab":{"base_uri":"https://localhost:8080/","height":664},"outputId":"b485ded9-9bf8-4806-f2c6-6b2e2b114ad7","trusted":true},"cell_type":"code","source":"fig, axes = plt.subplots(1, 1, figsize=(16, 10), sharex=True)\nax = sns.boxplot(data=pt_sp3, x='PlayKey', y='speed',\n            whis=\"range\", hue=\"wea\", palette = \"vlag\",dodge=False)\nax.set_ylabel('Speed')\nax.set_xlabel('Players')\nax.set_title(\"Boxplot of Speed for Injuried Players by Weather\")","execution_count":null,"outputs":[]},{"metadata":{"id":"kVe-QLh5Bty2","colab_type":"text"},"cell_type":"markdown","source":"There is no significant speed difference for injuried players with respect to weather conditions. Interestingly, there are more sunny and cloudy days than rainy days when players got injuried."},{"metadata":{},"cell_type":"markdown","source":"**Direction Analysis**"},{"metadata":{"id":"pP36_q6eH-zU","colab_type":"code","colab":{},"trusted":true},"cell_type":"code","source":"pt_sp_N = pt_sp3[pt_sp3['Surface']==\"Natural\"]\npt_sp_S = pt_sp3[pt_sp3['Surface']==\"Synthetic\"]","execution_count":null,"outputs":[]},{"metadata":{"id":"21sCwqATHnXK","colab_type":"code","colab":{"base_uri":"https://localhost:8080/","height":170},"outputId":"9431b243-5323-4248-ef5d-6d0ae06fac59","trusted":true},"cell_type":"code","source":"pt_sp_N['PlayKey'].unique()","execution_count":null,"outputs":[]},{"metadata":{"id":"vXGoOKONEV3V","colab_type":"code","colab":{},"trusted":true},"cell_type":"code","source":"p31070_3_7 = pt_sp3[pt_sp3['PlayKey'] == \"31070-3-7\"]\np33337_8_15 = pt_sp3[pt_sp3['PlayKey'] == \"33337-8-15\"]\np33474_19_7 = pt_sp3[pt_sp3['PlayKey'] == \"33474-19-7\"]\np34347_5_9 = pt_sp3[pt_sp3['PlayKey'] == \"34347-5-9\"]\np35570_15_35 = pt_sp3[pt_sp3['PlayKey'] == \"35570-15-35\"]\np36559_12_65 = pt_sp3[pt_sp3['PlayKey'] == \"36559-12-65\"]\np36621_13_58 = pt_sp3[pt_sp3['PlayKey'] == \"36621-13-58\"]\np38192_8_8 = pt_sp3[pt_sp3['PlayKey'] == \"38192-8-8\"]\np38876_29_14 = pt_sp3[pt_sp3['PlayKey'] == \"38876-29-14\"]\np39956_2_14 = pt_sp3[pt_sp3['PlayKey'] == \"39956-2-14\"]","execution_count":null,"outputs":[]},{"metadata":{"id":"ZO0k3UWrFk38","colab_type":"code","colab":{},"trusted":true},"cell_type":"code","source":"court = plt.imread(\"../input/football2/football.jpg\")","execution_count":null,"outputs":[]},{"metadata":{"id":"89LVMzmQ4vrR","colab_type":"code","colab":{"base_uri":"https://localhost:8080/","height":628},"outputId":"215997f6-4493-40b0-9b98-9fb8eb117343","trusted":true},"cell_type":"code","source":"plt.figure(figsize=(15, 11.5))\n\n# Plot the movemnts as scatter plot\n# using a colormap to show change in game clock\nplt.scatter(p31070_3_7.x, p31070_3_7.y, c=p31070_3_7.time,\n            cmap=plt.cm.Blues, s=50, zorder=1)\nplt.scatter(p33337_8_15.x, p33337_8_15.y, c=p33337_8_15.time,\n            cmap=plt.cm.Blues, s=50, zorder=1)\nplt.scatter(p33474_19_7.x, p33474_19_7.y, c=p33474_19_7.time,\n            cmap=plt.cm.Blues, s=50, zorder=1)\nplt.scatter(p34347_5_9.x, p34347_5_9.y, c=p34347_5_9.time,\n            cmap=plt.cm.Blues, s=50, zorder=1)\nplt.scatter(p35570_15_35.x, p35570_15_35.y, c=p35570_15_35.time,\n            cmap=plt.cm.Blues, s=50, zorder=1)\nplt.scatter(p36559_12_65.x, p36559_12_65.y, c=p36559_12_65.time,\n            cmap=plt.cm.Blues, s=50, zorder=1)\nplt.scatter(p36621_13_58.x, p36621_13_58.y, c=p36621_13_58.time,\n            cmap=plt.cm.Blues, s=50, zorder=1)\nplt.scatter(p38192_8_8.x, p38192_8_8.y, c=p38192_8_8.time,\n            cmap=plt.cm.Blues, s=50, zorder=1)\nplt.scatter(p38876_29_14.x, p38876_29_14.y, c=p38876_29_14.time,\n            cmap=plt.cm.Blues, s=50, zorder=1)\nplt.scatter(p39956_2_14.x, p39956_2_14.y, c=p39956_2_14.time,\n            cmap=plt.cm.Blues, s=50, zorder=1)\n# Darker colors represent moments earlier on in the game\ncbar = plt.colorbar(orientation=\"horizontal\")\ncbar.ax.invert_xaxis()\n\nplt.imshow(court, zorder=0, extent=[0,120,-10,60])\n\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"id":"V6-4frQDJzKR","colab_type":"code","colab":{"base_uri":"https://localhost:8080/","height":187},"outputId":"8222ca6b-a8fb-454c-f43d-7cf903fb9449","trusted":true},"cell_type":"code","source":"pt_sp_S['PlayKey'].unique()","execution_count":null,"outputs":[]},{"metadata":{"id":"Th63D-OFJ6Hy","colab_type":"code","colab":{},"trusted":true},"cell_type":"code","source":"p35611_7_42 = pt_sp3[pt_sp3['PlayKey'] == \"35611-7-42\"]\np36557_1_70 = pt_sp3[pt_sp3['PlayKey'] == \"36557-1-70\"]\np36607_16_19 = pt_sp3[pt_sp3['PlayKey'] == \"36607-16-19\"]\np38228_1_4 = pt_sp3[pt_sp3['PlayKey'] == \"38228-1-4\"]\np38364_5_23 = pt_sp3[pt_sp3['PlayKey'] == \"38364-5-23\"]\np39656_2_38 = pt_sp3[pt_sp3['PlayKey'] == \"39656-2-38\"]\np39678_2_1 = pt_sp3[pt_sp3['PlayKey'] == \"39678-2-1\"]\np39850_9_2 = pt_sp3[pt_sp3['PlayKey'] == \"39850-9-2\"]\np39873_4_32 = pt_sp3[pt_sp3['PlayKey'] == \"39873-4-32\"]\np40474_1_8 = pt_sp3[pt_sp3['PlayKey'] == \"40474-1-8\"]","execution_count":null,"outputs":[]},{"metadata":{"id":"MprkJoUOKdlk","colab_type":"code","colab":{"base_uri":"https://localhost:8080/","height":628},"outputId":"d5f72c41-61d9-45ee-a92b-106dc2f1b515","trusted":true},"cell_type":"code","source":"plt.figure(figsize=(15, 11.5))\n\n# Plot the movemnts as scatter plot\n# using a colormap to show change in game clock\nplt.scatter(p35611_7_42.x, p35611_7_42.y, c=p35611_7_42.time,\n            cmap=plt.cm.Blues, s=50, zorder=1)\nplt.scatter(p36557_1_70.x, p36557_1_70.y, c=p36557_1_70.time,\n            cmap=plt.cm.Blues, s=50, zorder=1)\nplt.scatter(p36607_16_19.x, p36607_16_19.y, c=p36607_16_19.time,\n            cmap=plt.cm.Blues, s=50, zorder=1)\nplt.scatter(p38228_1_4.x, p38228_1_4.y, c=p38228_1_4.time,\n            cmap=plt.cm.Blues, s=50, zorder=1)\nplt.scatter(p38364_5_23.x, p38364_5_23.y, c=p38364_5_23.time,\n            cmap=plt.cm.Blues, s=50, zorder=1)\nplt.scatter(p39656_2_38.x, p39656_2_38.y, c=p39656_2_38.time,\n            cmap=plt.cm.Blues, s=50, zorder=1)\nplt.scatter(p39678_2_1.x, p39678_2_1.y, c=p39678_2_1.time,\n            cmap=plt.cm.Blues, s=50, zorder=1)\nplt.scatter(p39850_9_2.x, p39850_9_2.y, c=p39850_9_2.time,\n            cmap=plt.cm.Blues, s=50, zorder=1)\nplt.scatter(p39873_4_32.x, p39873_4_32.y, c=p39873_4_32.time,\n            cmap=plt.cm.Blues, s=50, zorder=1)\nplt.scatter(p40474_1_8.x, p40474_1_8.y, c=p40474_1_8.time,\n            cmap=plt.cm.Blues, s=50, zorder=1)\n# Darker colors represent moments earlier on in the game\ncbar = plt.colorbar(orientation=\"horizontal\")\ncbar.ax.invert_xaxis()\n\nplt.imshow(court, zorder=0, extent=[0,120,-10,60])\n\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"It seems that injuried players on natural surfaces are more likely to make turns/direction changes than on synthetic surfaces. However, whether the surface has an impact on players' movement need more investigation on the data."},{"metadata":{"id":"jmP-uSTcLuC4","colab_type":"code","colab":{},"trusted":true},"cell_type":"code","source":"p_largeDC = pt_sp3[pt_sp3['dc']>=120]\np_smallDC = pt_sp3[pt_sp3['dc']<120]","execution_count":null,"outputs":[]},{"metadata":{"id":"b9Hr4IH9MS1O","colab_type":"code","colab":{"base_uri":"https://localhost:8080/","height":34},"outputId":"ec9a4555-e0cf-414c-c43f-1279f1d54b0e","trusted":true},"cell_type":"code","source":"p_largeDC['speed'].mean()","execution_count":null,"outputs":[]},{"metadata":{"id":"s8Btg1IkMkKy","colab_type":"code","colab":{"base_uri":"https://localhost:8080/","height":34},"outputId":"ed1d46ae-49f8-4974-8fb5-7599c5cbac74","trusted":true},"cell_type":"code","source":"p_smallDC['speed'].mean()","execution_count":null,"outputs":[]},{"metadata":{"id":"kFt7UHpl24Tm","colab_type":"text"},"cell_type":"markdown","source":"**Spatial Analysis** "},{"metadata":{"id":"AN6MRjiNC88S","colab_type":"text"},"cell_type":"markdown","source":"Where do injuried players play in the game?"},{"metadata":{"id":"efS5NZPMx8gv","colab_type":"code","colab":{"base_uri":"https://localhost:8080/","height":454},"outputId":"07e11a92-f087-4481-c037-83ee4ad14fd9","trusted":true},"cell_type":"code","source":"sns.jointplot(x=pt_sp2[\"x\"], y=pt_sp2[\"y\"], kind='hex', marginal_kws=dict(bins=50, rug=True))","execution_count":null,"outputs":[]},{"metadata":{"id":"YdqttVeS3lBj","colab_type":"code","colab":{"base_uri":"https://localhost:8080/","height":454},"outputId":"ec79f4f4-5d9f-44e4-8d6f-a033216ba6f6","trusted":true},"cell_type":"code","source":"#sns.jointplot(x=df[\"sepal_length\"], y=df[\"sepal_width\"], kind='kde', color=\"grey\", space=0)\n \n# Huge space\nsns.jointplot(x=pt_sp2[\"x\"], y=pt_sp2[\"y\"], kind='kde', color=\"grey\", space=3)\n \n# Make marginal bigger:\n#sns.jointplot(x=df[\"sepal_length\"], y=df[\"sepal_width\"], kind='kde',ratio=1)\n","execution_count":null,"outputs":[]},{"metadata":{"id":"9U4D9nUX4FFp","colab_type":"text"},"cell_type":"markdown","source":"Injuried players are more clustered in the middle area of the playground."},{"metadata":{},"cell_type":"markdown","source":"**2.3 Exploratory Data Analysis**"},{"metadata":{"id":"5m9ftfUtbBzk","colab_type":"code","colab":{},"trusted":true},"cell_type":"code","source":"ff = playlist['PlayKey'].isin(injuries['PlayKey'])\nin_list = playlist[ff]\nout_list = playlist[~ff]","execution_count":null,"outputs":[]},{"metadata":{"id":"pZaN39PicL6U","colab_type":"code","colab":{},"trusted":true},"cell_type":"code","source":"in_list['injuried'] = [\"Y\"] * 76\nout_list['injuried'] = [\"N\"] * 266929","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"merged = pd.concat([in_list, out_list])\nmerged.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"w2 = []\n\nfor wea in merged['Weather']:\n  if (wea == \"Sunny\" or wea == \"Clear and warm\" or wea == \"Clear Skies\" or wea == \"Clear skies\" or wea == \"Mostly Sunny\"or wea == \"Mostly sunny\"or wea == \"Clear\"):\n    w2.append(1)\n  elif(wea == \"Partly Cloudy\" or wea == \"Controlled Climate\" or wea == \"Cloudy\" or wea == \"Mostly cloudy\" or wea == \"Sun & clouds\" or wea == \"Coudy\" or wea == \"Cloudy and Cool\" ):\n    w2.append(2)\n  elif(wea == \"Rain\"or wea == \"Light Rain\"or wea == \"Rain shower\" or wea ==\"Cloudy with periods of rain, thunder possible. Winds shifting to WNW, 10-20 mph.\" or wea ==\"Fair\" or wea ==\"Cloudy, 50% change of rain\" ):\n    w2.append(3)\n  elif(wea == \"Indoors\"or wea ==\"Indoor\"):\n    w2.append(4)\n  elif(wea == \"Cold\"):\n    w2.append(5)\n  else:\n    w2.append(6)\n    \nmerged['wea'] = w2","execution_count":null,"outputs":[]},{"metadata":{"id":"2HWI4nbwNlDE","colab_type":"code","colab":{},"trusted":true},"cell_type":"code","source":"def hexbin(x, y, color, **kwargs):\n    cmap = sns.light_palette(color, as_cmap=True)\n    plt.hexbin(x, y, gridsize=10, cmap=cmap, **kwargs)\n\nwith sns.axes_style(\"dark\"):\n    g = sns.FacetGrid(merged, col=\"FieldType\", height=4)\ng.map(hexbin, \"wea\", \"Temperature\", extent=[0, 10, 0, 100]);","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"merged = merged[merged['Temperature']>0]","execution_count":null,"outputs":[]},{"metadata":{"id":"X8-sj8eYO0vU","colab_type":"code","colab":{"base_uri":"https://localhost:8080/","height":69},"outputId":"ac7159e7-d276-4382-ec66-a320df380630","trusted":true},"cell_type":"code","source":"sns.catplot(x=\"wea\", y=\"Temperature\", hue=\"FieldType\", kind=\"box\", data=merged)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"sns.catplot(x=\"FieldType\", col=\"wea\", col_wrap=6, kind=\"count\", palette=\"ch:.25\", data=merged)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"It is interesting that usage of natural playgrounds is mostly on sunny and cloudy days with higher temperature. Usage of synthetic grounds is mostly on cloudy days with relatively cooler temperature."},{"metadata":{"trusted":true},"cell_type":"code","source":"sns.catplot(x=\"FieldType\", col=\"wea\", col_wrap=6, kind=\"count\", palette=\"ch:.25\", data=merged[merged['injuried']==\"Y\"])","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Although the use of natural surface is a lot more than synthetic surface on sunny and cloudy days, there is more injuried on synthetic surface on cloudy days. This probably infer that synthetic surface has higher risk of injury on sunny and cloudy days."}],"metadata":{"colab":{"name":"NFL.ipynb","provenance":[]},"kernelspec":{"name":"python3","display_name":"Python 3"}},"nbformat":4,"nbformat_minor":1}