{"cells":[{"metadata":{"_kg_hide-input":true,"_kg_hide-output":false,"trusted":true,"_uuid":"a7d11cb9ce0a4139d577b1831e70fffc546c11f4"},"cell_type":"code","source":"from IPython.display import HTML\nimport numpy as np\nimport pandas as pd\nfrom matplotlib import pyplot as plt\nimport os\nimport warnings\nwarnings.filterwarnings('ignore')","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"a5164c1c5cf47478032ff41819cab825bba05675"},"cell_type":"markdown","source":"Contributors: Bryant Hales, Cole Schmitz, Sean Connors, Chris Macdonald, Isaac Plutzer\n\nClick [here](https://docs.google.com/presentation/d/1Xy9MSJfTulc7irhDQ-ppdZF3qHrLyamHBTVDKwjmHs4/edit?usp=sharing) to go through our presentation slides in full:\n\nIn the 2016 and 2017 NFL seasons, there were 37 concussions sustained on punt plays. The aim of this project is to find impactful solutions that could reduce that number of concussions sustained on punt plays that don’t alter the spirit of the game of football.\n\n# Table of Contents\n1. [Table of Contents](#Table of Contents)\n2. [Introduction](#Introduction)\n3. [Proposed Solution 1](#Proposed Solution 1)\n4. [Proposed Solution 2](#Proposed Solution 2)\n5. [Conclusion](#Conclusion)\n    \n# Introduction \n\nPunt plays are exciting for the fans, integral to the game, and not especially dangerous, and thus should have a place in the game going forward.\n\n## *Exciting For Fans*\n\nTake this punt play from the Denver Broncos vs Oakland Raiders game on Christmas Eve 2018. This Dwayne Harris return turned a matchup between two unremarkable teams on its head with what will surely turn out to be one of the most exciting plays of the 2018 NFL Season."},{"metadata":{"_kg_hide-input":true,"trusted":true,"_uuid":"ae51b54f73a374e8da8ef5ebb5690e9637242966"},"cell_type":"code","source":"HTML('<blockquote class=\"twitter-tweet\" data-lang=\"en\"><p lang=\"en\" dir=\"ltr\">WHAT A PLAY. \\n Dwayne Harris goes 99 YARDS for a punt return TD! <a href=\"https://twitter.com/hashtag/RaiderNation?src=hash&amp;ref_src=twsrc%5Etfw\">#RaiderNation</a> | <a href=\"https://twitter.com/hashtag/DENvsOAK?src=hash&amp;ref_src=twsrc%5Etfw\">#DENvsOAK</a> <a href=\"https://t.co/fjEkxMKg0C\">pic.twitter.com/fjEkxMKg0C</a></p>&mdash; NFL (@NFL) <a href=\"https://twitter.com/NFL/status/1077375040507629569?ref_src=twsrc%5Etfw\">2018. december 24.</a></blockquote>'\n'<script async src=\"https://platform.twitter.com/widgets.js\" charset=\"utf-8\"></script>')","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"7b37b2d70ce14a68a48137eeb2fb87bec855b53a"},"cell_type":"markdown","source":"As you can see, that video has been viewed over 2.4 million times and the tweet was retweeted over 4k times, making it one of the NFL’s most popular tweets in the month of December.\n\n## *Integral To The Game*\n\nIn addition to being exciting, punt plays are integral to the game. In the 2016 and 2017 regular seasons, there were [9.8 punt plays per game](https://docs.google.com/spreadsheets/d/1D7RcNTMMzVhM2YyQjiThZ7QQrqMxzlcEMDJy8PqTz5g/edit?usp=sharing), there were [20 touchdowns from punt returns](https://docs.google.com/spreadsheets/d/1Yw_WfVY2NaeYGQdrs4gnJqFeUs_RFXfs-AMIPMPgbcg/edit?usp=sharing), and the [average punt return went for about 8 yards](https://docs.google.com/spreadsheets/d/1Yw_WfVY2NaeYGQdrs4gnJqFeUs_RFXfs-AMIPMPgbcg/edit?usp=sharing).\n\n## *Not Terribly Dangerous, But Can Be Dangerous*\n\nUnlike [kickoff plays that had disproportionate rates of concussions per play](https://www.sbnation.com/2018/5/22/17369774/nfl-kickoff-rule-change-explained), we found that in the 2016 and 2017 regular seasons, [the rate of concussion per punt play was in line with the rates of concussion on other plays](https://docs.google.com/spreadsheets/d/1V0nCBsq8VsalywXVgP38woHHsfICcAyKq_2OL3rml94/edit#gid=0).\n\nHowever, punt plays still can be dangerous due to the high speed collisions that can happen during them. \n\nFor example, in the video below, Texans’ returner Braxton Miller jogged out to receive a punt. After the catch, Miller attempts to squeeze up the sideline for an extra 5-10 yards. Then a Titans gunner lays Miller out with a vicious tackle.\n\nMiller would not return to the game and missed the Texans next two contests due to a concussion sustained on the play."},{"metadata":{"trusted":true,"_uuid":"c95ca2a93742d6c0821daddc54de7fe4558be81f","_kg_hide-input":true,"_kg_hide-output":false},"cell_type":"code","source":"HTML('<video width=\"560\" height=\"315\" controls> <source src=\"http://a.video.nfl.com//films/vodzilla/153323/Kern_55_yd_punt-iJvv7OOA-20181119_173911500_5000k.mp4 \" type=\"video/mp4\"></video>')","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"2a97b3642ba25bfc3a4725462d61f0bbce11c469"},"cell_type":"markdown","source":"The main point of this presentation is to reduce the dangerous plays like the one above  that increase the risk of concussions for players. We believe that the best way to do this is by making a slight change to the NFL season and incentivising the punt returner to call for a fair catch. "},{"metadata":{"_uuid":"6a67a6dd52ebda02432490287d50e85b89820042"},"cell_type":"markdown","source":"# Proposed Solution 1: New NFL Schedule Structure\nOur proposed schedule change would reduce the number of preseason games to two games.  With the extra two weeks, the regular season would be lengthened to 19 weeks which would include two bye weeks and 17 games.  From a business, sporting, and player safety perspective, this change makes sense.  \n\n## *Business*\nFirst, fans are not really paying attention in the preseason, according to [Google Search interest](https://docs.google.com/spreadsheets/d/1Atd7EDA0BcZbtWZXSe5I8217tE9db3hMnQV9tyYMn7g/edit?usp=sharing).\n\n![Image][1]\n[1]: http://i66.tinypic.com/1zogp44.png\n\nSecond, fans are not really [watching the games](https://docs.google.com/spreadsheets/d/1So5c9bmV923NU__DPYSPJAGVJmOHZUUAklqrR_DkFJQ/edit#gid=0) until the regular season starts.\n\n![Image][2]\n[2]: http://i65.tinypic.com/s4x7ko.png\nTV Ratings from [STVPlus](https://stvplus.com/ratings) and [Sports Media Watch](http://www.sportsmediawatch.com/nfl-tv-ratings-viewership-nbc-cbs-fox-espn-nfln-regular-season-playoffs/2/).\n\n## *Sporting*\nIn addition, the NFL preseason is longer the preseason of any other major American sport, [when comparing the amount of preseason games to the amount of regular season games](https://docs.google.com/spreadsheets/d/19IA33ESUC5mROx-WIj3P0cehp9vrn9HmXVkDrCjDcEA/edit?usp=sharing).\n\n![Image][3]\n[3]: http://i64.tinypic.com/2hevd7d.png\n\nPlus, almost everybody around the league believes that the current preseason is too long. Take it from Roger Goodell, current NFL commissioner, [who has said](https://www.newsday.com/sports/football/roger-goodell-wants-nfl-preseason-reduced-to-three-games-1.13950784): “When I go around to fans, that’s maybe the No. 1 thing I hear. The NFL should do things to the highest possible standards. Preseason games are not that.” and “There’s value to them, building a team, evaluating players, but there are other ways of doing that. I think we could do it in three (games). Almost every coach has agreed we could get done what we need to in three games.” \n\n## *Player Safety*\nFinally and most importantly, eliminating two preseason games and adding a bye week and regular season game should slightly decrease the number of concussions.\n\nAccording to six years of data from [Play Smart Play Safe](https://www.playsmartplaysafe.com/newsroom/reports/2017-injury-data/), the rate of concussions per game in preseason has been [slightly higher](https://docs.google.com/spreadsheets/d/1V0nCBsq8VsalywXVgP38woHHsfICcAyKq_2OL3rml94/edit?usp=sharing) than the rate of concussions per game\t in the regular season and postseason.\n\nAdditionally, the rate of concussions per preseason punt play was [slightly higher](https://docs.google.com/spreadsheets/d/1sib7FM204teLM83-a6ITYQcy1e55bC3snt-EOcbtRdw/edit?usp=sharing) than the rate of concussions per regular season and postseason punt play in the 2016 and 2017 NFL Seasons.\n\nWhile these differences may not be statistically significant, we do believe that there are some qualities about preseason games that make them inherently more dangerous than regular season games and postseason games. We dove into the data to try to figure out some of those qualities…\n\nA potential reason for the difference is that there [are more fair catches called](https://docs.google.com/spreadsheets/d/1mCPhJNR66rKrZlr7myGy-FSOYxym0_kbdfoHjJUZ0W8/edit?usp=sharing) in the regular season and postseason than called in the preseason, [and plays with fair catches ended up with fewer concussions than plays without fair catches](https://docs.google.com/spreadsheets/d/1PfLQQhwnABIDlPnxK4NYsyzi51Lx-w_CMXWMKmr7lmc/edit#gid=0).\n\n![Image][4]\n[4]: http://i64.tinypic.com/r9h1cy.png\n\nFinally, there are about [1.4 more punt plays in preseason games than there are in regular season games](https://docs.google.com/spreadsheets/d/1RdApn1HI75-h19OCKZkiya0uQwftPRwE2ZlIGBB-d8k/edit?usp=sharing). As these preseason games gain more value, we believe the number of punts per preseason game will fall closer in line with the regular season figure, and there will be slight safety improvements.\n\nOn punt plays, we found that plays are traveling at slower plays as the season progresses.  The average max speed of players during the preseason was found to be 20.7 mph, but then in the postseason, the average max speed was significantly lower at 11.7 mph.\n\n![Image][15]\n[15]: http://i65.tinypic.com/2e31t9d.png\n\nWe believe that the faster the players are traveling, the more likely a concussion occur.  \n\nThere are many factors at play during the preseason special teams play.  These players are more likely to be on the bubble of making the team and are therefore playing for their job.  This could account for the increase in speed and increase in concussions as players are playing faster and harder during these games.\n\nWe also believe that experience plays a factor in concussions during punts.  Using the next gen stats, we were able to calculated the number of punt plays each player had been on.  We found that the average number of punt plays each player had participated in during the preseason was 107 plays.  This number jumps to 173 plays during the regular season and 183 during the postseason.  This shows that players are more experienced not in the preseason.  Players have more coaching and more game awareness during the regular/post season.  This could account for the reduce in concussions.\n\n![Image][16]\n[16]: http://i67.tinypic.com/famtky.png\n\nAdditionally, players cover more distance on punt plays in the preseason than they do in the regular season or post season. This is, again, probably related to the experience of the players and is another reason that there can be an increased risk of concussions in preseason punt plays.\n\n![Image][17]\n[17]: http://i64.tinypic.com/2s0gya9.png\n"},{"metadata":{"_uuid":"d239645bb5cf77a1aba08c2c0a2a5cf7027b53fb"},"cell_type":"markdown","source":"## *Impact*\nSo after the schedule alterations, an example schedule could look like this:\n\n![Image][5]\n[5]: http://i66.tinypic.com/1zce1qs.png\n\nWith a schedule of cuts that looks like this:\n\n![Image][6]\n[6]: http://i66.tinypic.com/v42xi8.png\n\n\nNow, coaches have to use the controlled environment of practice to make more roster decisions, which should leader to safer outcomes.\n\nWe believe that this schedule change will lead to about 400 fewer punt plays in the preseason, and the punt plays that do occur during the preseason will be safer.\n\nTo conclude, there is evidence from [coaches](https://www.newsday.com/sports/football/roger-goodell-wants-nfl-preseason-reduced-to-three-games-1.13950784), [owners](https://sportsday.dallasnews.com/dallas-cowboys/cowboys/2018/08/28/jerry-jones-adding-2-regular-season-games-reducing-preseason-create-safer-game-players), [fans](https://www.newsday.com/sports/football/roger-goodell-wants-nfl-preseason-reduced-to-three-games-1.13950784), and [players](https://ftw.usatoday.com/2018/08/rams-todd-gurley-is-very-excited-to-skip-the-preseason) that this schedule alteration would be a compromise that everyone could accept and could be implemented."},{"metadata":{"_uuid":"2aae1f134cdcdc7a155ff00cac9ed23ee96e6ed3"},"cell_type":"markdown","source":"# Proposed Solution 2: Fair Catch Rule\n\nOur proposed fair catch rule would advance the ball 8 yards on a fair catch.  The punt returner would still be forced to catch the ball and then from the spot of the catch, the ball would be advanced 8 yards to start the drive.  This rule makes sense from a player safety, entertainment, and spirit of the game perspective. \n\n## *Player Safety*\n\n*After successfully completing a fair catch, the punt returner’s team will begin their offensive drive with a 1st and 10 eight yards ahead of the spot where the fair catch was made. For example, if Deion Sanders of the Atlanta Falcons were to successfully fair catch a punt at his team’s **32 yard line**, Atlanta would start the offensive drive with a 1st and 10 at their own **40 yard line***. \n\n*The ball will not be advanced if the player attempting the fair catch muffs the fair catch and he and or team later recovers the ball.*\n\n*The punt returner must be given a reasonable opportunity to catch the punt while it is in the air, an interference penalty will be awarded, and the returning team will start the offensive drive 15 yards from the spot of the foul. Furthermore, if the referee deems the hit on the returner egregious, the referee has the authority to eject the tackler from the game.*\n\nBy incentivising the punt returner to fair catch, our goal is to greatly reduce the number of concussion that occur.  Fair catches greatly reduce the chances that a concussion will occur on a punt play.  [Concussions occur in .1% of punt plays when the ball if fair caught.  Where as, concussion occur in .7% of punt plays when the ball is not fair caught](https://docs.google.com/spreadsheets/d/1PfLQQhwnABIDlPnxK4NYsyzi51Lx-w_CMXWMKmr7lmc/edit?usp=sharing)\n\n![Image][7]\n[7]: http://i65.tinypic.com/opoe14.png\n\n\n"},{"metadata":{"_uuid":"5426030c4a09b26e46476d0ee6c9b52e8b1e7406"},"cell_type":"markdown","source":"Once this rule is in place, punting strategy may change slightly. One of the ways it could change is that the added 8 yards from a fair catch would incentivise punters to kick the ball out of bounds to avoid the extra 8 yards. \n\nBut we believe this will make punts safer. [There were 640 punts which landed out of bounds in the 2016 and 2017 seasons. Out of the 640 punt plays, there were zero recorded concussions on those plays](https://docs.google.com/spreadsheets/d/1KjGhsxXYR4I-rvc0q9XpFJDVN5z1PjbI0ZrzY_nxSJk/edit?usp=sharing).\n\nSimilarly,  if the punter is trying to punt the ball out of bounds and he mishits and the ball stays inbounds, we still believe that punts will become safer. [We found the chance of a concussion occuring to be greatly reduced if the punt is within 15 yards of either sideline](https://docs.google.com/spreadsheets/d/179nfwQ9z9TwXuGGaPbKprhSkIk26AMN4uH86Rw_CRs0/edit?usp=sharing).\n\n![Image][8]\n[8]: http://i67.tinypic.com/10p7fqd.png"},{"metadata":{"_uuid":"da7037b76186771b4199aca492f9ecaa50f617da"},"cell_type":"markdown","source":"Another way that punting strategy could change is that coaches might want to instruct the gunners to get down the field and down the ball before the returner has an opportunity to catch it to avoid the yards, which could lead to more potential speed, contact, and therefore more concussions.\n\nBut we believe with the way that we wrote the rule and with the potential for ejection, gunner speed and contact will probably decrease. Basically, with that part of the rule, we are trying to get rid of plays that look like this:"},{"metadata":{"_kg_hide-input":true,"trusted":true,"_uuid":"e7c54c7eb5bd690491aba9d9b5b0d5128abd6a97"},"cell_type":"code","source":"HTML('<video width=\"560\" height=\"315\" controls> <source src=\"https://nfl-vod.cdn.anvato.net/league/5691/18/11/25/284956/284956_12D27120C06E4DB994040750FB43991D_181125_284956_way_punt_3200.mp4\" type=\"video/mp4\"></video>')","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"9ab9f9247f829bbb54d137d8ae4d3120bada1319"},"cell_type":"markdown","source":"So overall, we believe that there are multiple facets of this idea that will make punt plays safer.\n\n## *Entertainment*\n\nBefore we we get into the ratings and entertainment aspect of football, we need to first look at where teams end up at after a punt- We took a random sample of 15 punts to identify punt [location](https://docs.google.com/spreadsheets/d/1NzYL3xKS-05GtJG56Zo7ZkR3WPCbZGxWp45km_vfWNc/edit?usp=sharing) and where the opponent drive starts.\n\n![Image][9]\n[9]: http://i66.tinypic.com/n9dh2.png\n\nAlmost every fan loves to watch a high scoring game.  This was seen in the Week 11 Monday night game between the Rams and the Chiefs.  [The pregame Vegas point totals for the game were between 63 and 64 points](https://www.sbnation.com/2018/11/19/18104042/kansas-city-chiefs-los-angeles-rams-over-under-betting-line-total-mnf), meaning it was known before the game that there was going to be a lot of points scored. A [record number of people tuned in to watch two high scoring offenses face off](https://edition.cnn.com/2018/11/20/media/nfl-ratings-rams-chiefs/index.html). The game had the highest TV rating of any Monday Night Football game since 2014.\n\nLooking at offensive [drives](https://docs.google.com/spreadsheets/d/1AsxJ-sNqiycffDVlkvpT9_TUznqJKQp9MkyuoI-ycpo/edit?usp=sharing) after punts in the NFL 2016 and 2017 regular seasons, we can determine a team is expected to score more points the further they start from their own goal line. Implementing a rule that moves fair catches forward will therefore protect player safety while also increasing the points in a game. \n\n![Image][10]\n[10]: http://i65.tinypic.com/qwztcy.png\n\n![Image][11]\n[11]: http://i64.tinypic.com/2uz5bpv.jpg\n\nIt should come as no surprise that teams score more points on drives when they receive the ball closer to the opponent's end zone.  Mathematically speaking, the number of points scored based on the yardline can be modeled exponentially.  As seen in graph 2 above, the bar graph is modeled by the equation,\n\ny=.9002e.1466x\t\t\t\t  (eqn. 1).\n\nEven though advancing the ball 8 yards from a fair catch would only increase the number of points scored marginally, it could account for a few points a game.\n\n\n## *Spirit of the Game*\n\nThe game of football is sacred and steeped in tradition. The sport is dangerous in nature, so to make the game safer can easily change the foundation of the sport.  We kept that in mind when attempting to reduce severe and irreversible harm to the players that comes in the form of concussions. \n\n[The average punt return distance in the NFL and FBS over the last three seasons, 2015, 2016, and 2017](https://docs.google.com/spreadsheets/d/1kOVLb4b02JnWHaU1Hgb_nWWdLOK-Y4wR3EG6PwJA_gs/edit?usp=sharing), was just over 8.4 yards for both levels.  This lead us to arriving at 8 yards for the distance after a fair catch.  This is why we believe that that adding an extra 8 yards for a far catch will not only make the game safer, but will also keep the game of football the same.  We believe that 8 yards will not impact the flow of games. \n\n![Image][12]\n[12]: http://i68.tinypic.com/2885kxt.png\n\n[We ran a linear regression model using average yards per punt to predict 4th down attempts in the 2017 season](https://docs.google.com/spreadsheets/d/1eDEOh3-PLd1xQi1G0CW2y89gyp0OiMyTaDf8a-v5yAU/edit).  In the linear regression model, the r-squared was tremendously low, .00002 which shows that there are other factors that influences a coaches decision on fourth down than the ability of one’s punter.  For reference, the difference in average punting distance between the longest and shortest punter in the NFL was 7.5 yards.  Those 7.5 did not affect a coaches decision to punt or to for it on fourth down.  Due to this fact, we determined that the 8 yards from a fair catch will not affect a coaches decision on fourth down.  If there are marginal increases in fourth down attempts, the game will only be more fun to watch. \n\n\n## *Impact*\n\nSo to recap, on the safety side, more fair catches, more punts out of bounds and more punts closer to the sideline, should all help to reduce concussions on punt plays. In addition, the new rule where players can be ejected for attempting an egregious hit on the punt returner will continue to incentivize punt team players to proceed with caution around punt returners.\n\nLastly, we also believe this rule will lead to slightly more scoring, which will make the game more exciting, but it will also preserve the flow of the game."},{"metadata":{"_uuid":"344c3723f97cee88b8c1e7dc2b879df78117b1f1"},"cell_type":"markdown","source":"# Conclusion\n\nSo to recap, we believe that we can slightly reduce the amount of concussions from punt plays by making a slight change to the NFL season and incentivising the punt returner to call for a fair catch. \n\nWhile these solutions are not particularly innovative (like as innovative as the [Schiano plan for making kickoffs safer](https://www.nj.com/rutgersfootball/index.ssf/2011/06/politi_inspired_by_eric_legran.html#incart_mce), for example), we believed that an innovative solution was not necessary, as punt plays are not terribly dangerous. \n\nWe also considered mandating certain formations for the punt return team, but decided that these two changes would be the best at this time.\n\nThank you for viewing our presentation, and feedback is appreciated!\n\nAnd here is a little bit about us: \n\n![Image][13]\n[13]: http://i68.tinypic.com/2dakeqg.png"},{"metadata":{"trusted":true,"_uuid":"2b98c7d3ebf14a1c4db4b63344b732de8b45b164"},"cell_type":"code","source":"# Reading in NGS Data...\npre2016 = pd.read_csv('/kaggle/input/NGS-2016-pre.csv')\npre2017 = pd.read_csv('/kaggle/input/NGS-2017-pre.csv')\nreg2016_1 = pd.read_csv('/kaggle/input/NGS-2016-reg-wk1-6.csv')\nreg2016_2 = pd.read_csv('/kaggle/input/NGS-2016-reg-wk7-12.csv')\nreg2016_3 = pd.read_csv('/kaggle/input/NGS-2016-reg-wk13-17.csv')\nreg2017_1 = pd.read_csv('/kaggle/input/NGS-2017-reg-wk1-6.csv')\nreg2017_2 = pd.read_csv('/kaggle/input/NGS-2017-reg-wk7-12.csv')\nreg2017_3 = pd.read_csv('/kaggle/input/NGS-2017-reg-wk13-17.csv')\npost2016 = pd.read_csv('/kaggle/input/NGS-2016-post.csv')\npost2017 = pd.read_csv('/kaggle/input/NGS-2017-post.csv')\n\n#Catch Location Data:\nplay_info['catch_x'] = 0\nplay_info['catch_y'] = 0\n#counter = 0\nfor file in [pre2016,pre2017,reg2016_1,reg2016_2,reg2016_3,reg2017_1,reg2017_2,reg2017_3,post2016,post2017]:\n    for game in file.GameKey.unique():\n        for playid in file[file.GameKey == game].PlayID.unique():\n            try:\n                returner_GSISID = PPRD[PPRD.GameKey == game][PPRD.PlayID == playid][PPRD.Role == 'PR'].GSISID.values[0]\n            except:\n                returner_GSISID = 0\n            #print(returner_GSISID)\n            #print(playid)\n            #print(game)\n            #print(file)\n            catch_x = -10\n            catch_y = -10\n            try:\n                catch_x = file[file.GameKey == game][file.PlayID == playid][file.GSISID == returner_GSISID][file.Event == 'punt_received'].x.values[0]\n                catch_y = file[file.GameKey == game][file.PlayID == playid][file.GSISID == returner_GSISID][file.Event == 'punt_received'].y.values[0]\n            except:\n                catch_x = file[file.GameKey == game][file.PlayID == playid][file.GSISID == returner_GSISID][file.Event == 'punt_received'].x.values\n                catch_y = file[file.GameKey == game][file.PlayID == playid][file.GSISID == returner_GSISID][file.Event == 'punt_received'].y.values\n            if catch_x == []:\n                catch_x = -10\n            if catch_y == []:\n                catch_y = -10\n            try:\n                play_info.loc[(play_info.GameKey == game) & (play_info.PlayID == playid), 'catch_x'] = catch_x\n                play_info.loc[(play_info.GameKey == game) & (play_info.PlayID == playid), 'catch_y'] = catch_y\n            except:\n                play_info.loc[(play_info.GameKey == game) & (play_info.PlayID == playid), 'catch_x'] = -10\n                play_info.loc[(play_info.GameKey == game) & (play_info.PlayID == playid), 'catch_y'] = -10\n                \n# Making Measurements from NGS Data...\n\n#Add approprate columns to Play Info Here:\nplay_info['avg_avg_speed'] = 0\nplay_info['avg_max_speed'] = 0\nplay_info['avg_dist_covered'] = 0\nplay_info['total_collisions'] = 0\nplay_info['hang_time'] = 0\nplay_info['catch_x'] = 0\nplay_info['catch_y'] = 0\nmaxspd = []\ndist = []\navspd = []\nb = 0\n# Iterate through all players and plays and compute values...\nfor file in [reg2017_1,reg2017_2,reg2017_3]:\n    for game in file.GameKey.unique():\n        for playid in file[file.GameKey == game].PlayID.unique():\n            #Play-level values here\n            avspeeds = [] #\n            maxspeeds = [] #\n            distances_covered = [] #\n            collisions = []\n            hang_time = 0 #\n            catch_x = 0 #\n            catch_y = 0 #\n            for player in file[file.GameKey == game][file.PlayID == playid].GSISID.unique():\n                xvals = file[file.GameKey == game][file.PlayID == playid][file.GSISID == player].sort_values(by=['Time']).x.values\n                yvals = file[file.GameKey == game][file.PlayID == playid][file.GSISID == player].sort_values(by=['Time']).y.values\n                disvals = file[file.GameKey == game][file.PlayID == playid][file.GSISID == player].sort_values(by=['Time']).dis.values\n                ovals = file[file.GameKey == game][file.PlayID == playid][file.GSISID == player].sort_values(by=['Time']).o.values\n                dirvals = file[file.GameKey == game][file.PlayID == playid][file.GSISID == player].sort_values(by=['Time']).dir.values\n                events = file[file.GameKey == game][file.PlayID == playid][file.GSISID == player].sort_values(by=['Time']).Event.values\n                \n                # Hang-Time and Catch Location\n                if PPRD[PPRD.GameKey == game][PPRD.PlayID == playid][PPRD.GSISID == player].Role.values == 'PR':\n                    recieved_index = 0\n                    for i in range(len(events)):\n                        if events[i] == 'punt':\n                            punt_index = i\n                        if events[i] == 'punt_recieved':\n                            recieved_index = i\n                    hang_time = (recieved_index-punt_index)/10\n                    catch_x = xvals[recieved_index]\n                    catch_y = yvals[recieved_index]\n                    \n                # Distance, Speed, and Collisions\n                pos_change = []\n                speed = []\n                play_started = False\n                play_not_finished = True\n                i = 0\n                play_going = True\n                while (i < len(xvals)) & play_going:\n                    if i == 0:\n                        dP = 0\n                    else:\n                        dP = (((xvals[i] - xvals[i-1])**2)+((yvals[i] - yvals[i-1])**2))**(.5)\n                    if events[i] == 'ball_snap':\n                        play_started = True\n                    if events[i] == 'tackle':\n                        play_going = False\n                    pos_change.append(dP)\n                    speed.append(dP*10) # 1/10th of second timesteps\n                    i = i+1\n                avspeeds.append(np.mean(speed))\n                if len(speed) == 0:\n                    maxspeeds.append(-1)\n                else:\n                    maxspeeds.append(np.max(speed))\n                distances_covered.append(np.sum(pos_change))\n                #print('Did a player')\n            collisions = [0] #placeholder value\n            play_info.loc[(play_info.GameKey == game) & (play_info.PlayID == playid), 'avg_avg_speed'] = np.mean(avspeeds)\n            play_info.loc[(play_info.GameKey == game) & (play_info.PlayID == playid), 'avg_max_speed'] = np.mean(maxspeeds)\n            play_info.loc[(play_info.GameKey == game) & (play_info.PlayID == playid), 'avg_dist_covered'] = np.mean(distances_covered)\n            maxspd.append(np.mean(maxspeeds))\n            avspd.append(np.mean(avspeeds))\n            dist.append(np.mean(distances_covered))\n            \nplay_info.to_csv('play_info_with_measurements.csv',index = False)","execution_count":null,"outputs":[]}],"metadata":{"kernelspec":{"display_name":"Python 3","language":"python","name":"python3"},"language_info":{"name":"python","version":"3.6.6","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"}},"nbformat":4,"nbformat_minor":1}