{"cells":[{"metadata":{},"cell_type":"markdown","source":"# NFL 1st and Future - Analytics\n### Can you investigate the relationship between the playing surface and the injury and performance of NFL athletes?\nIn 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\nYou'll also notice there isn't a leaderboard, and you are not required to develop a predictive model. This isn't a traditional supervised Kaggle machine learning competition. For more information on this challenge format, see this forum thread. This challenge is part of NFL 1st & Future, the NFL’s annual Super Bowl competition designed to spur innovation in player health, safety and performance.\n\n## About The NFL\n\nThe National Football League is America's most popular sports league, comprised of 32 franchises that compete each year to win the Super Bowl, the world's biggest annual sporting event. Founded in 1920, the NFL developed the model for the successful modern sports league, including national and international distribution, extensive revenue sharing, competitive excellence, and strong franchises across the country.\n\nThe NFL is committed to advancing progress in the diagnosis, prevention and treatment of sports-related injuries. The NFL's ongoing health and safety efforts include support for independent medical research and engineering advancements and a commitment to work to better protect players and make the game safer, including enhancements to medical protocols and improvements to how our game is taught and played.\n\nAs more is learned, the league evaluates and changes rules to evolve the game and try to improve protections for players. Since 2002 alone, the NFL has made 50 rules changes intended to eliminate potentially dangerous tactics and reduce the risk of injuries.\n\nFor more information about the NFL's health and safety efforts, please visit www.PlaySmartPlaySafe.com"},{"metadata":{"trusted":true,"_kg_hide-input":true,"_kg_hide-output":true},"cell_type":"code","source":"import pandas as pd\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport seaborn as sns\nimport os\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n\n%matplotlib inline","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"games=pd.read_csv('/kaggle/input/nfl-playing-surface-analytics/PlayList.csv')\ninjrec=pd.read_csv('/kaggle/input/nfl-playing-surface-analytics/InjuryRecord.csv')","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Data preparation\nWe need set up a data for good analyze and visualisation. At first, I removed the nan values. Others was replaced by nan. In the column PlayType Not Returnded and Returnded were removed to group the Punt and Kickoff PlayType."},{"metadata":{"trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"games.fillna({'StadiumType': 'NoData',\n                     'Weather': 'NoData',\n                     }, inplace=True)\n\ngames.fillna(method='ffill', inplace=True)\n\ngames.replace('Missing Data', np.nan, inplace=True)\n\ngames['Temperature'].replace(-999, np.nan, inplace=True)\n\ngames.PlayType=games.PlayType.str.replace('Not Returned', '').str.replace('Returned', '').str.strip()\ngames.PlayType.replace('0', np.nan, inplace=True)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"There is a serious data problem in the Weather Column. It may be noticed that the same or similar values in this column have written differently, like Coudy, cloudy, Indoor, Indoors. Therefore, I decided to group all the weather values into several types: Sunny, Clear, Cloudy, Partly Cloudy, Controled Climate, Rain and Bad."},{"metadata":{"_kg_hide-input":true,"trusted":true},"cell_type":"code","source":"games.Weather=games.Weather.replace({'Indoors': 'Controlled Climate', 'Rain': 'Rain and Bad', \n                                     'N/A (Indoors)': 'Controlled Climate', 'Snow': 'Rain and Bad',\n                                     'Indoor': 'Controlled Climate', 'Overcast': 'Rain and Bad',\n                                     'N/A Indoor': 'Controlled Climate', 'Clear and cold': 'Clear',\n                                     'Mostly Cloudy': 'Cloudy', 'Sunny and clear': 'Sunny',\n                                     'Mostly cloudy': 'Cloudy', 'Rain Chance 40%': 'Rain and Bad',\n                                     'Cloudy and cold': 'Cloudy', 'Sunny, highs to upper 80s': 'Sunny',\n                                     'Cloudy and Cool': 'Cloudy', 'Cloudy, light snow accumulating 1-3\"': 'Rain and Bad',\n                                     'Partly cloudy': 'Partly Cloudy', 'Scattered Showers': 'Rain and Bad',\n                                     'Party Cloudy': 'Partly Cloudy', 'Cold': 'Rain and Bad',\n                                     'Partly Clouidy': 'Partly Cloudy', 'Sunny and cold': 'Sunny', \n                                     'Mostly Coudy': 'Partly Cloudy', 'Partly sunny': 'Sunny',\n                                     'cloudy': 'Cloudy', 'Cloudy, fog started developing in 2nd quarter ': 'Rain and Bad',\n                                     'Coudy': 'Cloudy', 'Showers': 'Rain and Bad',\n                                     'Mostly Sunny': 'Sunny', 'Rainy': 'Rain and Bad',\n                                     'Partly Sunny': 'Sunny', 'Clear to Partly Cloudy': 'Partly Cloudy',\n                                     'Mostly sunny': 'Sunny', 'Rain shower': 'Rain and Bad',\n                                     'Sunny Skies': 'Sunny', 'Heat Index 95': 'Rain and Bad',\n                                     'Sunny and warm': 'Sunny', 'Cloudy, Rain': 'Rain and Bad',\n                                     'Clear and Sunny': 'Clear', 'Heavy lake effect snow': 'Rain and Bad',\n                                     'Clear and sunny': 'Clear', '30% Chance of Rain': 'Rain and Bad', \n                                     'Mostly Sunny Skies': 'Sunny', 'Cloudy, chance of rain ': 'Rain and Bad',\n                                     'Clear Skies': 'Clear', 'Cloudy, 50% change of rain': 'Rain and Bad',\n                                     'Clear skies': 'Clear', 'Rain likely, temps in low 40s.': 'Rain and Bad',\n                                     'Clear and Cool': 'Clear', 'Sunny, Windy': 'Sunny',\n                                     'Fair': 'Clear', 'Cloudy, fog started developing in 2nd quarter': 'Rain and Bad',\n                                     'Light Rain': 'Rain and Bad', '10% Chance of Rain': 'Rain and Bad',\n                                     'Clear and warm': 'Clear', 'Cloudy, chance of rain': 'Cloudy',\n                                     'Hazy': 'Cloudy', 'Partly clear': 'Clear', 'Sun & clouds': 'Sunny',\n'Cloudy with periods of rain, thunder possible. Winds shifting to WNW, 10-20 mph.': 'Rain and Bad'})     ","execution_count":null,"outputs":[]},{"metadata":{"_kg_hide-input":true,"trusted":true},"cell_type":"code","source":"games.Weather=games.Weather.replace({'Controlled Climate': 'CC',\n                                    'Rain and Bad': 'RaB',\n                                    'Clear': 'Cr',\n                                    'Sunny': 'Sun',\n                                    'Partly Cloudy': 'PC',\n                                    'Cloudy': 'Cl',\n                                    'NoData': 'ND'})","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"The next step was to combine the data from the two tdata frames. Since, there was not full data in the data frame with injuries, merge gave out only 77 rows, which was wrong and needed to be fixed."},{"metadata":{"trusted":true},"cell_type":"code","source":"injrec_full=pd.merge(games, injrec)\ninjrec_full.shape","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"First of all, I created data frame with all injury data using the \"right\" merge. Then, I grouped all injuries in one column and saw missed data."},{"metadata":{"trusted":true},"cell_type":"code","source":"injrec_full=pd.merge(games, injrec, how='right')\ninjrec_full['Injuries']=injrec_full[['DM_M1', 'DM_M7', 'DM_M28', 'DM_M42']].sum(axis=1)\ninj_dict={1: 'Fine', 2: 'Little problem', 3: 'Serious Trouble', 4: 'Catastrophic Event'}\ninjrec_full['Injuries']=injrec_full['Injuries'].map(inj_dict)\ninjrec_full.drop(['DM_M1','DM_M7', 'DM_M28', 'DM_M42'], axis=1, inplace=True)\ninjrec_full.tail(3)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Because there were no values in PlayKey, data frames were not be able to merge. Therefore, to get the full data I needed to find another way. We know the GameID and can assume that the injury occurred in the last PlayKey. Let's make a loop that will form a data frame with the necessary data."},{"metadata":{"trusted":true},"cell_type":"code","source":"miss_data=games.loc[games['GameID']=='33337-2'].tail(1)\nfor i in range(78, len(injrec_full)):\n    miss_data=miss_data.append(games.loc[games['GameID']==injrec_full.iloc[i][1]].tail(1))","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"But the merge didn't work with this data frame, so again I needed another way. I used append and then used function."},{"metadata":{"trusted":true},"cell_type":"code","source":"miss_data_new=pd.merge(miss_data, injrec_full)\nmiss_data_new.shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"injrec_full=injrec_full.append(miss_data, sort=False)\n\ndef get_column_array(injrec_full, column):\n    expected_length = len(injrec_full)\n    current_array = injrec_full[column].dropna().values\n    if len(current_array) < expected_length:\n        current_array = np.append(current_array, [''] * (expected_length - len(current_array)))\n    return current_array\n\ninjrec_full=pd.DataFrame({column: get_column_array(injrec_full, column) for column in injrec_full.columns})\n\ninjrec_full.replace('', np.nan, inplace=True)\ninjrec_full=injrec_full.dropna(thresh=10)\ninjrec_full.tail(3)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"I got the desired data frame, but still needed to fix the type of columns that had changed from manipulation."},{"metadata":{"trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"injrec_full['Temperature']=injrec_full['Temperature'].astype(float)\ninjrec_full['PlayerDay']=injrec_full['PlayerDay'].astype(float)\ninjrec_full['PlayerGame']=injrec_full['PlayerGame'].astype(float)\ninjrec_full['PlayerGamePlay']=injrec_full['PlayerGamePlay'].astype(float)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Visualization\n## Injuries\nFinally, I began to visualize the data. According to the graphs, the ratio of injuries and the number of games by field type showed that the synthetic surface is 1.7 times more dangerous than natural."},{"metadata":{"trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"sns.set(rc={'axes.labelsize':30,\n            'figure.figsize':(13.7,10.27),\n            'xtick.labelsize':25,\n            'ytick.labelsize':20})","execution_count":null,"outputs":[]},{"metadata":{"_kg_hide-input":true,"trusted":true},"cell_type":"code","source":"fig, axs = plt.subplots(1, 2)\n\naxs[0].pie(injrec['Surface'].value_counts(),\n           autopct='%1.0f%%',\n          colors=['#CDC70A', '#2A741B'],\n          textprops={'fontsize': 18},\n          shadow=True)\n\naxs[1].pie(games['FieldType'].value_counts(),\n           autopct='%1.0f%%',\n           startangle=180,\n          colors=['#2A741B', '#CDC70A'],\n           textprops={'fontsize': 18},\n          shadow=True)\n\naxs[0].set_title('Distribution of Injuries by Surface',\n                    fontsize= 24)\n\naxs[1].set_title('Distribution of games by Surface',\n                     fontsize= 24)\n\naxs[1].legend(labels=games['FieldType'].value_counts().index,\n    loc='upper right',\n    prop={'size': 18},\n     bbox_to_anchor=(1.4, 0.9),\n             title='Surface',\n             title_fontsize='28')\n\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"On the synthetic surface, there are more Serious and Catastrophic injuries.\n"},{"metadata":{"_kg_hide-input":true,"trusted":true},"cell_type":"code","source":"chart=sns.countplot(x='Surface',hue='Injuries',data=injrec_full, \n              palette=['#820108', '#FF4C56', '#EEF10B', '#0BF1CE'],\n             edgecolor=(0,0,0),\n                  linewidth=2)\n\nchart.legend(prop={'size': 22},\n     bbox_to_anchor=(1, 0.9),\n            title='Injuries',\n            title_fontsize='35')\n\nchart.set_title('Surface Injury Distribution',\n               fontsize=40)\n\nchart.set(yticks=range(0, 21,2))\n\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"The synthetic surface has more ankle and toes injuries."},{"metadata":{"_kg_hide-input":true,"trusted":true},"cell_type":"code","source":"chart=sns.catplot(x='BodyPart', hue='Injuries', data=injrec_full, col='Surface', kind='count',\n                  palette=['#820108', '#FF4C56', '#EEF10B', '#0BF1CE'],edgecolor=(0,0,0),\n                  linewidth=2, legend=False)\n\nchart.set_xticklabels(size=20)\n\nchart.set_xlabels(size=24)\n\nchart.set(yticks=range(0, 13,2))\n\nchart.add_legend(prop={'size': 18},\n            title='Injuries',\n            title_fontsize='30')\n\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Visual Injuries by Play Type\nIt can be seen that Rush and Puss play types have the most injuries. But for the final conclusions we need to look at the game ratio."},{"metadata":{"_kg_hide-input":true,"trusted":true},"cell_type":"code","source":"chart1=sns.countplot(x='PlayType', hue='Injuries', data=injrec_full, \n              palette=['#820108', '#FF4C56', '#EEF10B', '#0BF1CE'],\n             edgecolor=(0,0,0),\n                  linewidth=2)\n\nchart1.set_title('Distribution of Injuries by Play Type',\n                     fontsize= 38)\n\nchart1.legend(prop={'size': 22},\n     bbox_to_anchor=(1, 0.9), title='Injuries',\n            title_fontsize='35')\n\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Based on the number of games, it is clear that Kickoff and Punt play types are more dangerous."},{"metadata":{"_kg_hide-input":true,"trusted":true},"cell_type":"code","source":"fig, axs = plt.subplots(1, 2)\n\naxs[0].pie(injrec_full['PlayType'].value_counts(),\n           radius=1.25,\n           autopct='%1.0f%%',\n           explode=(0, 0, 0.1, 0.2, 0),\n           colors=['#094275', '#FA7D0F', '#0BA006', '#FF4513', '#DDE30F'],\n           textprops={'fontsize': 18},\n           shadow=True)\n\naxs[1].pie(games['PlayType'].value_counts(),\n           radius=1.25,\n           autopct='%1.0f%%',\n           explode=(0, 0, 0.2, 0.3, 0, 0),\n           #startangle=180,\n           colors=['#094275', '#FA7D0F', '#FF4513','#0BA006', '#7536A7', '#DDE30F'],\n           textprops={'fontsize': 18},\n           shadow=True)\n\naxs[0].set_title('Distribution of Injuries by Play Type',\n                     fontsize= 22)\n\naxs[1].set_title('Distribution of games by Play Type',\n                     fontsize= 22)\n\naxs[1].legend(labels=games['PlayType'].value_counts().index,\n    loc='upper right',\n    prop={'size': 18},\n     bbox_to_anchor=(1.6, 0.9),\n             title='Play Type',\n             title_fontsize='28')\n\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"All play types take more injuries on the synthetic surface."},{"metadata":{"_kg_hide-input":true,"trusted":true},"cell_type":"code","source":"chart=sns.catplot(x='PlayType', hue='Injuries', data=injrec_full, col='Surface', kind='count',\n                  palette=['#820108', '#FF4C56', '#EEF10B', '#0BF1CE'],edgecolor=(0,0,0),\n                  linewidth=2, legend=False)\n\nchart.set_xticklabels(size=15)\n\nchart.set_xlabels(size=24)\n\nchart.set(yticks=range(0, 13,2))\n\nchart.add_legend(prop={'size': 18},\n            title='Injuries',\n            title_fontsize='30')\n\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"On the synthetic surface Pass play type get more ankle injuries."},{"metadata":{"_kg_hide-input":true,"trusted":true},"cell_type":"code","source":"chart=sns.catplot(x='PlayType', hue='BodyPart', data=injrec_full, col='Surface', kind='count',\n                  palette=['#272A7C', '#1696C6', '#1E7928', '#CCE914', '#FF0000'],edgecolor=(0,0,0),\n                  linewidth=2, legend=False)\n\nchart.set_xticklabels(size=15)\n\nchart.set_xlabels(size=24)\n\nchart.add_legend(prop={'size': 18},\n            title='Injuries',\n            title_fontsize='30')\n\nchart.set(yticks=range(0, 15,2))\n\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Position Group\nBy the distribution of injuries and the total number of games, the safe group position OL is clearly visible. The most dangerous positions are WR, RB, TE"},{"metadata":{"_kg_hide-input":true,"trusted":true},"cell_type":"code","source":"fig, axs = plt.subplots(1, 2)\n\naxs[0].pie(injrec_full['PositionGroup'].value_counts(),\n           radius=1.2,\n           autopct='%1.0f%%',\n           explode=(0, 0.1, 0, 0.2, 0, 0.2, 0.1),\n          colors=['#8E08FE' ,'#258187', '#A525B9', '#D6D676', '#D11C4D', '#2B8138', '#C49144'],\n           textprops={'fontsize': 18},\n          shadow=True)\n\naxs[1].pie(games['PositionGroup'].value_counts(),\n           radius=1.2,\n           autopct='%1.0f%%',\n            explode=(0, 0, 0.1, 0.1, 0, 0.25, 0.1, 0, 0),\n          colors=['#8E08FE', '#A525B9', '#2B8138','#258187', '#D11C4D', '#D6D676', '#C49144', '#F96905', '#D1BFB2'],\n           textprops={'fontsize': 18},\n          shadow=True)\n\naxs[0].set_title('Position Group Injury Distribution',\n                     fontsize= 24)\n\naxs[1].set_title('Position Group Games Distribution',\n                     fontsize= 24)\n\naxs[1].legend(labels=games['PositionGroup'].value_counts().index,\n    loc='upper right',\n    prop={'size': 16},\n     bbox_to_anchor=(1.7, 0.9),\n             title='Position Group',\n             title_fontsize='28')\n\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"_kg_hide-input":true,"trusted":true},"cell_type":"code","source":"chart1=sns.countplot(x='PositionGroup', hue='Injuries', data=injrec_full, \n              palette=['#820108', '#FF4C56', '#EEF10B', '#0BF1CE'],\n             edgecolor=(0,0,0),\n                  linewidth=2)\n\nchart1.set_title('Distribution of Injuries by Position Group',\n                     fontsize= 38)\n\nchart1.legend(prop={'size': 22},\n     bbox_to_anchor=(1, 0.9), title='Injuries',\n            title_fontsize='35')\n\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"DB and WR position groups are more dangerous on the synthetic field, but for OL position synthetic surface is really good."},{"metadata":{"_kg_hide-input":true,"trusted":true},"cell_type":"code","source":"chart=sns.catplot(x='PositionGroup', hue='Injuries', data=injrec_full, col='Surface', kind='count',\n                  palette=['#820108', '#FF4C56', '#EEF10B', '#0BF1CE'],edgecolor=(0,0,0),\n                  linewidth=2, legend=False)\n\nchart.set_xticklabels(size=15)\n\nchart.set_xlabels(size=24)\n\nchart.set(yticks=range(0, 13,2))\n\nchart.add_legend(prop={'size': 18},\n            title='Injuries',\n            title_fontsize='30')\n\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"DB has more ankle injuries on the synthetic field."},{"metadata":{"trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"chart=sns.catplot(x='PositionGroup', hue='BodyPart', data=injrec_full, col='Surface', kind='count',\n                  palette=['#272A7C', '#1696C6', '#1E7928', '#CCE914', '#FF0000'],edgecolor=(0,0,0),\n                  linewidth=2, legend=False)\n                  #height=15, aspect=1)\n    \nchart.set_xticklabels(size=15)\n\nchart.set_xlabels(size=24)\n\nchart.add_legend(prop={'size': 18},\n            title='Injuries',\n            title_fontsize='30')\n\nchart.set(yticks=range(0, 13,2))\n\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Weather\nSunny, partly cloudy and clear weather are more dangerous. The safest weather is cloudy."},{"metadata":{"_kg_hide-input":true,"trusted":true},"cell_type":"code","source":"wth=['Cloudy', 'Sunny', 'Clear', 'Partly Cloudy','Rain and Bad', 'Controlled Climate', 'NoData']\n\nfig, axs = plt.subplots(1, 2)\n\naxs[0].pie(injrec_full['Weather'].value_counts(),\n           radius=1.2,\n           autopct='%1.0f%%',\n         explode=(0.1, 0, 0.1, 0, 0.2, 0.2, 0),\n          colors=['#F7FE00', '#498484', '#1550A0', '#B8CCF2', '#DE00FF', '#D2355D', '#453547' ],\n           textprops={'fontsize': 18},\n          shadow=True)\n\naxs[1].pie(games['Weather'].value_counts(),\n           radius=1.2,\n           autopct='%1.0f%%',\n            explode=(0.1, 0, 0.1, 0, 0.2, 0.2, 0),\n         colors=['#498484', '#F7FE00', '#B8CCF2','#1550A0', '#D2355D', '#DE00FF', '#453547'],\n           textprops={'fontsize': 18},\n          shadow=True)\n\naxs[0].set_title('Weather Injury Distribution',\n                     fontsize=24)\naxs[1].set_title('Weather Games Distribution',\n                     fontsize=24)\n\naxs[1].legend(labels=wth,\n    loc='upper right',\n    prop={'size': 20},\n     bbox_to_anchor=(1.8, 0.9),\n             title='Weather',\n             title_fontsize='28')\n\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"_kg_hide-input":true,"trusted":true},"cell_type":"code","source":"chart1=sns.countplot(x='Weather', hue='Injuries', data=injrec_full, \n              palette=['#820108', '#FF4C56', '#EEF10B', '#0BF1CE'],\n             edgecolor=(0,0,0),\n                  linewidth=2)\n\nchart1.set_title('Distribution of Injuries by Position Group',\n                     fontsize= 38)\n\nchart1.legend(prop={'size': 25},\n     bbox_to_anchor=(1, 0.9), title='Injuries',\n            title_fontsize='45')\n\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"_kg_hide-input":true,"trusted":true},"cell_type":"code","source":"chart=sns.catplot(x='Weather', hue='Injuries', data=injrec_full, col='Surface', kind='count', \n                  palette=['#820108', '#FF4C56', '#EEF10B', '#0BF1CE'],edgecolor=(0,0,0),\n                  linewidth=2, legend=False)\n\nchart.set_xticklabels(size=20)\n\nchart.set_xlabels(size=24)\n\nchart.set(yticks=range(0, 13,2))\n\nchart.add_legend(prop={'size': 18},\n            title='Injuries',\n            title_fontsize='80')\n\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"_kg_hide-input":true,"trusted":true},"cell_type":"code","source":"chart=sns.catplot(x='Weather', hue='BodyPart', data=injrec_full, col='Surface', kind='count',\n                  palette=['#272A7C', '#1696C6', '#1E7928', '#CCE914', '#FF0000'],edgecolor=(0,0,0),\n                  linewidth=2, legend=False)\n\nchart.set_xticklabels(size=20)\n\nchart.set_xlabels(size=24)\n\nchart.set(yticks=range(0, 13,2))\n\nchart.add_legend(prop={'size': 18},\n            title='Injuries',\n            title_fontsize='30')\n\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Comparisons"},{"metadata":{"_kg_hide-input":true,"trusted":true},"cell_type":"code","source":"labels=['Temperature', 'PlayerDay', 'PlayerGame', 'PlayerGamePlay']\nx=injrec_full[['Temperature', 'PlayerDay', 'PlayerGame', 'PlayerGamePlay']].mean().astype(int)\ny=games[['Temperature', 'PlayerDay', 'PlayerGame', 'PlayerGamePlay']].mean().astype(int)\nz = np.arange(len(x))  \nwidth = 0.35  \n\nfig, ax = plt.subplots()\n\nrects1 = ax.bar(z - width/2, x, width, label='Injuries games', edgecolor=(0,0,0),\n                  linewidth=2)\nrects2 = ax.bar(z + width/2, y, width, label='All Games', edgecolor=(0,0,0),\n                  linewidth=2)\n\nax.set_ylabel('Count')\nax.set_title('Average Comparison', fontsize=26)\nax.set_xticks(z)\nax.set_xticklabels(labels)\nax.legend( loc='upper right',\n    prop={'size': 20})\n\ndef autolabel(rects):\n    for rect in rects:\n        height = rect.get_height()\n        ax.annotate('{}'.format(height),\n                    xy=(rect.get_x() + rect.get_width() / 2, height),\n                    xytext=(0, 4), \n                    textcoords=\"offset points\",\n                    ha='center', va='bottom', size=20)\nautolabel(rects1)\nautolabel(rects2)\n\nfig.tight_layout()\nfig.set_size_inches(12, 8)\n\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"_kg_hide-input":true,"trusted":true},"cell_type":"code","source":"labels=['Temperature', 'PlayerDay', 'PlayerGame', 'PlayerGamePlay']\nx=injrec_full[['Temperature', 'PlayerDay', 'PlayerGame', 'PlayerGamePlay']].median().astype(int)\ny=games[['Temperature', 'PlayerDay', 'PlayerGame', 'PlayerGamePlay']].median().astype(int)\nz = np.arange(len(x))  \nwidth = 0.35 \n\nfig, ax = plt.subplots()\n\nrects1 = ax.bar(z - width/2, x, width, label='Injuries games', edgecolor=(0,0,0),\n                  linewidth=2)\nrects2 = ax.bar(z + width/2, y, width, label='All games', edgecolor=(0,0,0),\n                  linewidth=2)\n\nax.set_ylabel('Count')\nax.set_title('Median Comparison',  fontsize=26)\nax.set_xticks(z)\nax.set_xticklabels(labels)\nax.legend(loc='upper right',\n    prop={'size': 20})\n\ndef autolabel(rects):\n    for rect in rects:\n        height = rect.get_height()\n        ax.annotate('{}'.format(height),\n                    xy=(rect.get_x() + rect.get_width() / 2, height),\n                    xytext=(0, 3), \n                    textcoords=\"offset points\",\n                    ha='center', va='bottom',\n                    size=20)\nautolabel(rects1)\nautolabel(rects2)\n\nfig.tight_layout()\nfig.set_size_inches(12, 8)\n\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"_kg_hide-input":true,"trusted":true},"cell_type":"code","source":"fig = plt.figure()\nax = fig.suptitle('Distribution of Injured games and all games by', fontsize=36)\n\nax1=plt.subplot(221)\nsns.kdeplot(injrec_full['PlayerDay'], shade=True, color='#FF0000', legend=False)\nsns.kdeplot(games['PlayerDay'], shade=True, color='#002CF2', legend=False)\nax1.set_title('Player Day', fontsize=24)\n\nax2=plt.subplot(2, 2, 2)\nsns.kdeplot(injrec_full['PlayerGame'], shade=True, color='#FF0000', label='With Injuries')\nsns.kdeplot(games['PlayerGame'], shade=True, color='#002CF2', label='All')\nplt.legend(loc='upper right',\n           bbox_to_anchor=(1.75, 0.9),\n    prop={'size': 24},\n          title='Games',\n             title_fontsize='28')\nax2.set_title('Player Game', fontsize=24)\n\nax3=plt.subplot(2, 2, 3)\nsns.kdeplot(injrec_full['PlayerGamePlay'], shade=True, color='#FF0000', legend=False)\nsns.kdeplot(games['PlayerGamePlay'], shade=True, color='#002CF2', legend=False)\nax3.set_title('Player Game Play', fontsize=24)\n\nax4=plt.subplot(2, 2, 4)\nsns.kdeplot(injrec_full['Temperature'], shade=True, color='#FF0000', legend=False)\nsns.kdeplot(games['Temperature'], shade=True, color='#002CF2', legend=False)\nax4.set_title('Temperature', fontsize=24)\n\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Conclusion\n1.1. Synthetic surface is 1.7 times more dangerous than natural one.\n\n1.2. The knee and ankle are most prone to injury. At the same time, the risk of ankle injury is significantly higher on the synthetic surface (8 vs 3). Knee injuries are almost the same on the both surfaces. Also, synthetic coating is much more dangerous for the toe. (6 vs 1)\n\n1.3. But it is worth noting that catastrophic (M42) foot injuries are clearly higher on natural surfaces (1 vs. 4).\n\n2.1. Most injured players Rush and Pass play type, but this is due to their advantage in the number of games. Based on the game to injury ratio, Punt and Kickoff players have more injuries. With 4% and 5% of the total number of games, the number of injuries is 14% and 11%, respectively.\n\n2.2. The synthetic surface is more dangerous for kickoff, since it gets more injuries on it (8 vs 4).\n\n2.3. Punt receives more injuries on the natural field (9 vs. 6), but they are mostly light, and the synthetic  injuries are dominated by severe injuries 3 catastrophic(M42) and 1 serious injury(M28).\n\n2.4. Rush and Pass players have greater risk of injury on the synthetic field, especially serious (M28) injuries (5 vs 2).\n\n2.5. The main injury of kickoff and punt players is on their knees (18 of 27).\n\n2.6.  The ankles and knees are almost subject  of the same danger (14 and 15 injuries) for rush and pass players on the natural field. The ankles are more at risk (21 injuries), even the knees are slightly smaller on the synthetic field than on the natural field (13 injuries).\n\n3.1. The most traumatic position - group Db, because it has the most games. Based on the game/injury ratio, the most dangerous position is RB. With 4% of games, it accounts for 9% of injuries. WR (16% of games and 22% of injuries), LB (19% of games and 22% of injuries) and TE (3% of games and 6% of injuries) also dangerous.\n\n3.2. The safest position is OL. With 18% of games, only 7% of injuries occure. QB is also not very dangerous . There are no injuries at 3% of games.\n\n3.3. The distribution of injuries is pretty similar across all roles. Mostly catastrophic injuries (M42) are in the RB position, and a large number of minor injuries (M7) are in the DB stand out.\n\n3.4. By type of field, the DB gets more injuries on the synthetic field (18 vs 10), and WR is more catastrophic (4 vs 1).\n\n3.5. An interesting point is that the OL position on the synthetic field got only light injuries (M1), and on the natural surface, there is as much as 2 catastrophic (M42). Otherwise, the positions are not much different.\n\n3.6. By injury to a part of the body, only the DB role has a strong difference. Many ankle injuries are on the synthetic field (11 vs 2).\n\n4.1. An interesting weather observation that the most dangerous is sunny, clear and partially cloudy weather, which also confirms the comparison of average and median temperatures. Moreover, there are the greatest number of catastrophic injuries in sunny weather (M42) (10).\n\n4.2. Bad weather and climate-controlled are also a little dangerous. With 8% of all games, injuries are 11%.\n\n4.3. And much safer is cloudy weather. With 29% of all injury games, it accounts for only 17%, which is almost two times less.\n\n4.4. In sunny weather, injuries end more disastrously (M42) on the natural field than on the artificial one. (6 vs 4).  The risk of minor (M7) injury on the natural field is much greater than on the synthetic one (12 vs 4) in clean and bad weather. \n\n4.5. There are mostly not serious injuries (6 light(M1), 4 minor (M7) and only 2 catastrophic (M42)) in the controlled climate, which is only on synthetic surface.  From this, I can conclude that in sunny weather with high temperature it is more reasonable to conduct a match on the synthetic surface with a controlled climate.\n\n5.1. The comparison of the average and median values of the number of games and days shows that the amount does not affect the risk of injury. On the contrary, all injuries are more likely in the middle of the season.\n\n5.2. The comparison of player game play shows that their number does not affect the risk of injury. On the contrary, if a player plays the danger zone (15-25), then the farther he plays the less chance of injury."}],"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}