Lesson 48 · Real-World Data Analytics
str.extract & Merges in Pandas: NFL Ticket Prices | Python Data Analytics #48
Returning to football from an economics angle. Two real FiveThirtyEight datasets: thirty-two real teams' 2014 real national average ticket prices, and…
- CourseReal-World Data Analytics
- Lesson48 of 100
- Video15 min
- FormatJupyter notebook · 30 code cells
- Data2 datasets
What you'll learn
Datasets used in this lesson
Save these next to the notebook. In Google Colab, upload them with the 📁 icon on the left first.
📓 Full notebook
Download .ipynbData Analytics 100, Video 48: Real NFL Ticket Pricing Analysis#
- Video forty-eight of the hundred-video real-world data analytics series, returning to football from an economics angle.
- Two real FiveThirtyEight datasets: thirty-two real teams' 2014 real national average ticket prices, and ninety-six real individual 2014 divisional matchup prices.
- Let's get into it.
This lesson is for learners who can already summarise a single table and are ready to combine two related tables. The business question is about pricing: which NFL teams and games command the highest ticket prices, and does a team's overall price level predict what fans pay for individual games? The data comes from two FiveThirtyEight files for the 2014 season. The first, national_average.csv, holds one national average ticket price for each of the 32 teams. The second, 2014_average_ticket_price.csv, holds 96 divisional matchups with the event description, the division and an average ticket price.
In this lesson you will:
- clean messy column names and team labels with string methods
- pull home and away teams out of a text description with a regular expression
- compare prices across divisions and conferences with
groupby - join the two tables with
mergeand measure a correlation
Prerequisites: you should be comfortable with groupby, sort_values and basic matplotlib charts. A little familiarity with regular expressions helps but is not required. Earlier lessons in the series cover these if you need a refresher.
Part 1: Real National Average Ticket Prices#
This lesson uses two files, so you start with the simpler one. The code imports pandas, numpy and matplotlib, reads national_average.csv into a DataFrame called national and checks .shape. The output is (32, 2): one row for each of the 32 NFL teams and two columns. A table this small is easy to check by eye, which makes it a good reference table to join onto the more detailed data later.
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
national = pd.read_csv('national_average.csv')
national.shape
Part 2: Real National Data Preview#
Looking at real rows reveals formatting problems that column names alone would hide. The code lists the columns and then shows head(5); only the last expression is displayed, so the output is the first five rows. Two issues stand out. The first column is oddly named Genre and every team name ends with the word 'Tickets', for example 'Arizona Cardinals Tickets'. The price column is called Avg TP, $, which contains spaces and symbols. Both will be cleaned up before the data is joined to anything.
national.columns.tolist()
national.head(5)
Part 3: Real Divisional Matchup Prices#
The second file holds the detail: individual divisional games. The code reads 2014_average_ticket_price.csv into a DataFrame called matchups and checks its shape. The output is (96, 3), so there are 96 games described by three columns. With 8 divisions in the NFL, 96 games works out at 12 per division, which a sanity check confirms at the end of the lesson. Knowing the expected size in advance makes it easier to spot a file that has loaded incorrectly.
matchups = pd.read_csv('2014_average_ticket_price.csv')
matchups.shape
Part 4: Real Matchup Data Preview#
As with the first file, a preview shows what the text looks like before you try to work with it. Only head(5) is displayed. Each Event reads like 'Baltimore Ravens at Pittsburgh Steelers Tickets on ...', so the away team comes first and the home team follows the word 'at'. The Division column holds labels such as 'AFC North', and prices sit in Avg TP, $. The first five games are all AFC North, with prices from $148 to $202. This 'X at Y' pattern is what the extraction step relies on later.
matchups.columns.tolist()
matchups.head(5)
Part 5: Real Missing Data Check#
Missing values would break joins and averages, so you check both tables. The code calls isna().sum() on national and then on matchups, but only the second result is displayed. It shows zero missing values in Event, Division and Avg TP, $. The national table check ran but its result is not shown, so wrap both calls in print() or run them separately if you want to see each one. The wrap-up of this lesson confirms neither table has gaps.
national.isna().sum()
matchups.isna().sum()
Part 6: Real Duplicate Row Check#
Duplicate rows would double-count games and distort averages. duplicated().sum() counts rows that exactly repeat an earlier row. The code runs it on both tables, but only the last result, for matchups, is displayed: 0 duplicates. As with the missing value check, run the national line on its own or wrap it in print() to see its result too. Checking both tables before a merge is good practice because duplicates in a lookup table multiply rows in the joined result.
national.duplicated().sum()
matchups.duplicated().sum()
Part 7: Real Team Name Cleanup#
Clean names make every later step easier to read and are required for the join to work. The code replaces the awkward column names with team_raw and national_avg_price by assigning a new list to national.columns. It then uses .str.replace(' Tickets', '', regex=False) to strip the trailing word from each team name and stores the result in a new team column. regex=False tells pandas to treat the text literally rather than as a pattern. The output shows clean names such as Arizona Cardinals at $109 and Baltimore Ravens at $140.
national.columns = ['team_raw', 'national_avg_price']
national['team'] = national['team_raw'].str.replace(' Tickets', '', regex=False)
national[['team', 'national_avg_price']].head(3)
Part 8: Real Priciest Teams Nationally#
Ranking teams by price answers the first business question directly. sort_values('national_avg_price', ascending=False) orders teams from most to least expensive and .head(5) keeps the top five. The Seattle Seahawks lead at $291, followed by the Denver Broncos and New England Patriots tied at $257, the Chicago Bears at $236 and the San Francisco 49ers at $221. The numbers on the left are the original row positions, which pandas keeps after sorting.
top_national = national.sort_values('national_avg_price', ascending=False).head(5)
top_national[['team', 'national_avg_price']]
Part 9: Real Cheapest Teams Nationally#
The cheapest teams are the other end of the same ranking. Sorting by price without ascending=False uses the default ascending order, so .head(5) returns the five lowest prices. The St Louis Rams are the cheapest at $48, well below the next team, the Kansas City Chiefs at $67, then the Minnesota Vikings at $71, Washington at $76 and the Oakland Raiders at $77. The gap between the dearest and cheapest teams is $243, so ticket prices vary widely across the league.
bottom_national = national.sort_values('national_avg_price').head(5)
bottom_national[['team', 'national_avg_price']]
Part 10: Real Top Team Prices Chart#
A chart of the top ten shows how quickly prices fall away from the leader. The code sorts teams by price, keeps ten, uses set_index('team') so team names become the bar labels, and plots horizontal bars. ax.invert_yaxis() flips the order so the most expensive team sits at the top rather than the bottom, which is how most readers expect a ranking. The chart is saved to top_team_prices.png and closed, so it does not display in the notebook. Open it to see how far Seattle stands out.
fig, ax = plt.subplots(figsize=(9, 6))
national.sort_values('national_avg_price', ascending=False).head(10).set_index('team')['national_avg_price'].plot(kind='barh', ax=ax, color='steelblue')
ax.invert_yaxis()
ax.set_xlabel('Real National Average Ticket Price, $')
ax.set_title('Real Ten Most Expensive NFL Teams by Ticket Price, 2014')
plt.tight_layout()
plt.savefig('top_team_prices.png', dpi=100)
plt.close()
Part 11: Real Home and Away Team Extraction#
To link games to teams you need team names in their own columns, not buried in a sentence. After renaming the columns, the code uses .str.extract with regular expressions (patterns that match text). r'^(.+?) at ' captures everything from the start of the text up to the first ' at ', which is the away team. r' at (.+?) Tickets on' captures the text between ' at ' and ' Tickets on', which is the home team. The ? makes each match as short as possible. The output shows, for example, the Baltimore Ravens as away team and the Pittsburgh Steelers as home team.
matchups.columns = ['event', 'division', 'matchup_avg_price']
matchups['away_team'] = matchups['event'].str.extract(r'^(.+?) at ')
matchups['home_team'] = matchups['event'].str.extract(r' at (.+?) Tickets on')
matchups[['event', 'away_team', 'home_team']].head(3)
Part 12: Real Extraction Sanity Check#
Regular expressions fail silently: when a pattern does not match, str.extract returns a missing value rather than an error. Counting missing values in the new columns is the quickest way to catch that. The output shows 0 missing values in both away_team and home_team, so every one of the 96 event descriptions followed the expected pattern. Always run a check like this after extracting text, before you rely on the new columns.
matchups[['away_team', 'home_team']].isna().sum()
Part 13: Real Average Price by Division#
Comparing divisions shows whether price differences follow geography and rivalries. The code groups games by division, averages matchup_avg_price, rounds to one decimal and sorts from highest to lowest. The NFC North is the most expensive at $178.6, followed by the NFC East at $172.9 and NFC West at $165.2. The AFC South is the cheapest at $83.3, just below the NFC South at $95.4. Three NFC divisions top the table, which hints at the conference comparison coming up.
division_avg = matchups.groupby('division')['matchup_avg_price'].mean().round(1).sort_values(ascending=False)
division_avg
Part 14: Real Division Average Chart#
A bar chart makes the gap between the top and bottom divisions easy to see. The code plots the division averages as horizontal bars and uses ax.invert_yaxis() so the most expensive division, the NFC North, appears at the top. Labels and a title are added, and the chart is saved to division_prices.png and closed, so it does not display in the notebook. When you open it, look for the step down between the three expensive NFC divisions and the AFC divisions below them.
fig, ax = plt.subplots(figsize=(9, 6))
division_avg.plot(kind='barh', ax=ax, color='firebrick')
ax.invert_yaxis()
ax.set_xlabel('Real Average Matchup Ticket Price, $')
ax.set_title('Real Average NFL Ticket Price by Division, 2014')
plt.tight_layout()
plt.savefig('division_prices.png', dpi=100)
plt.close()
Part 15: Real Priciest Individual Matchups#
Averages can hide individual games that are far more expensive than the rest. nlargest(5, 'matchup_avg_price') returns the five priciest games, keeping only the event, division and price columns. The Green Bay Packers at the Chicago Bears tops the list at $423, followed by the 49ers at Seattle at $373. The reverse fixtures, Bears at Packers and Seahawks at 49ers, are next at $265 and $264, then the Chargers at Denver at $241. Long-standing rivalries clearly matter, and where the game is played changes the price a lot.
top_matchups = matchups.nlargest(5, 'matchup_avg_price')[['event', 'division', 'matchup_avg_price']]
top_matchups
Part 16: Real Cheapest Individual Matchups#
The cheapest games help explain the low division averages. nsmallest(5, 'matchup_avg_price') returns the five lowest-priced games. The Arizona Cardinals at the St Louis Rams is the cheapest at $29, followed by the Chiefs at the Raiders and the Titans at the Jaguars, both at $40. Notice that the Rams and Raiders, two of the cheapest teams nationally, are home teams in this list. That pattern is what the correlation step tests properly.
bottom_matchups = matchups.nsmallest(5, 'matchup_avg_price')[['event', 'division', 'matchup_avg_price']]
bottom_matchups
Part 17: Real AFC vs NFC Comparison#
Grouping by conference gives a single headline comparison. Every division label starts with its conference, so .str[:3] takes the first three characters, 'AFC' or 'NFC', and stores them in a new conference column. The code then groups by conference and averages the game price. The output shows AFC games averaging $117.4 and NFC games $153.0, so NFC tickets cost about $36 more on average. Slicing text by position like this only works when the format is consistent, so check a few values first.
matchups['conference'] = matchups['division'].str[:3]
conf_avg = matchups.groupby('conference')['matchup_avg_price'].mean().round(1)
conf_avg
Part 18: Real Merge with National Averages#
To compare game prices with team price levels, the two tables must be joined. merge matches each game's home_team with the team column in national. left_on and right_on name the matching columns, and how='left' keeps every game even if no match is found. The code then counts missing national_avg_price values, and the output is 0, so every home team found a match. This is why the earlier name cleanup mattered: without removing ' Tickets', no rows would have matched.
merged = matchups.merge(national[['team', 'national_avg_price']], left_on='home_team', right_on='team', how='left')
merged['national_avg_price'].isna().sum()
Part 19: Real Price Correlation#
With both prices side by side you can measure how closely they move together. .corr() calculates the Pearson correlation coefficient, a number between -1 and 1 where values near 1 mean the two move up and down together and values near 0 mean no clear linear link. The output is 0.812, a strong positive relationship: games hosted by teams with high national averages also tend to have high game prices. Correlation describes association, not cause, so it does not tell you why a team's tickets are expensive.
price_corr = round(merged['matchup_avg_price'].corr(merged['national_avg_price']), 3)
price_corr
Part 20: Real Price Spread by Division#
Averages tell you the typical price, but the range tells you how uneven a division is. The code groups by division and uses .agg with a small lambda that subtracts the minimum price from the maximum, giving the range for each division. The NFC North has the widest spread at $356, driven by the $423 Packers at Bears game, and the NFC West follows at $344. The AFC North is the most consistent at $121. A wide range is a reminder that a single average can be misleading.
division_spread = matchups.groupby('division')['matchup_avg_price'].agg(lambda x: x.max() - x.min()).round(1).sort_values(ascending=False)
division_spread
Part 21: Real Teams Above League Median#
The median is the middle value when teams are sorted by price, and it is less affected by extreme values than the mean. The code calculates the median national price, then counts teams priced above it with a boolean comparison and .sum(). The output is (107.5, 16): the median is $107.50 and 16 teams sit above it. A median of 107.5 rather than a whole number happens because there is an even number of teams, so pandas averages the two middle values.
national_median = national['national_avg_price'].median()
above_median = (national['national_avg_price'] > national_median).sum()
national_median, above_median
Part 22: Real Share of Teams Above Median#
Turning the count into a percentage makes it easier to communicate. The code divides the 16 teams above the median by the 32 teams in total and multiplies by 100. The output is 50.0%. That is exactly what you should expect: by definition, half the values lie above the median when there is an even number of distinct values around it. This makes the step a useful check that the median was calculated correctly, rather than a new finding.
above_median_pct = round(above_median / len(national) * 100, 1)
above_median_pct
Part 23: Real Highest Individual Game Price#
Sometimes you need the whole row for the extreme value, not just the number. idxmax() returns the index label of the highest price, and .loc uses that label to fetch the full row. The output confirms the Green Bay Packers at Chicago Bears game in the NFC North at $423, the same game that topped the nlargest list. The Name: 48 at the bottom is the row's index label. Remember that idxmax() returns only the first match if there is a tie.
highest_game = matchups.loc[matchups['matchup_avg_price'].idxmax()]
highest_game[['event', 'division', 'matchup_avg_price']]
Part 24: Real Lowest Individual Game Price#
The same .loc and idxmin() pattern finds the single cheapest game. The output shows the Arizona Cardinals at the St Louis Rams in the NFC West at $29. It is striking that the NFC West contains both a $29 game and the $373 49ers at Seahawks game, which explains its wide price range. Pairing an extreme value with its context like this often tells a more interesting story than the number alone.
lowest_game = matchups.loc[matchups['matchup_avg_price'].idxmin()]
lowest_game[['event', 'division', 'matchup_avg_price']]
Part 25: Saving the Real Enriched Matchup Dataset#
Saving the merged table keeps the extracted teams, conference labels and national prices together for future analysis. to_csv writes merged to nfl_tickets_enriched.csv with index=False, so no extra index column is saved. The code then reloads the file and compares shapes, and the output True shows nothing was lost. Saving the merged table rather than the original matchups means the join does not have to be repeated next time.
merged.to_csv('nfl_tickets_enriched.csv', index=False)
reloaded = pd.read_csv('nfl_tickets_enriched.csv')
reloaded.shape == merged.shape
Part 26: Real Sanity Check, Team Count#
Before quoting team-level results you should confirm the table holds every team exactly once. nunique() counts distinct values in the cleaned team column, and comparing it with 32 returns True. This also confirms that removing ' Tickets' did not accidentally merge two teams into the same name. A check like this is especially useful after any text cleaning step.
national['team'].nunique() == 32
Part 27: Real Sanity Check, Matchups and Divisions#
This step checks the matchup table's structure in one line. It confirms there are 96 rows and that division has 8 distinct values, joining both tests with Python's and. The output True means both hold. If a division label had a typo or extra space, nunique() would return more than 8 and the check would fail, so this also guards against messy labels.
len(matchups) == 96 and matchups['division'].nunique() == 8
Part 28: Real Sanity Check, Twelve Games per Division#
Each NFL division has four teams that play each other twice, home and away, giving 12 divisional games per division. The code counts games per division with value_counts(), compares each count with 12, and .all() returns True only if every comparison is True. The output np.True_ confirms that each division has exactly 12 games, so the division averages compare like with like.
(matchups['division'].value_counts() == 12).all()
Part 29: Real Top Finding Print#
A finding becomes useful when you can say it in one sentence. The code takes the first row of top_national with .iloc[0] and reads the team name and price. The printed output says the priciest NFL team nationally in 2014 was the Seattle Seahawks, at an average of $291 per ticket. Because top_national was already sorted, the first row is guaranteed to be the most expensive team.
priciest_team = top_national.iloc[0]['team']
priciest_team_price = top_national.iloc[0]['national_avg_price']
print(f'The real priciest NFL team nationally in 2014 was the {priciest_team}, at a real average of ${priciest_team_price} per ticket.')
Part 30: Real Recap Print#
The recap combines the main results from both tables. The f-string uses the team and game counts, the correlation, and conf_avg.idxmax() and conf_avg.idxmin() to name the more and less expensive conferences automatically. The printed output says that across 32 teams and 96 matchups, a team's national average price correlated with its game prices at 0.812, and the NFC out-priced the AFC on average. Using idxmax() rather than typing 'NFC' keeps the sentence correct if the data changes.
print(f'Across {len(national)} real teams and {len(matchups)} real 2014 matchups, a real team national average price correlated with its real individual game prices at {price_corr}, and the {conf_avg.idxmax()} genuinely out-priced the {conf_avg.idxmin()} on average.')
Wrap-Up: What You Learned#
- This real lesson combined two real FiveThirtyEight 2014 datasets, thirty-two real teams' national average ticket prices and ninety-six real individual divisional matchup prices, with zero real missing or duplicate values in either.
- The Seattle Seahawks were the real priciest team nationally, while the St Louis Rams were the real most affordable, and NFC divisions consistently out-priced AFC divisions.
- A real home team's national average price correlated strongly with its real individual game prices, an honest, measurable real relationship rather than an assumed one.
- This real domain has now covered eight genuinely different competitive contexts, basketball, tennis, baseball twice, football twice, soccer, and chess, using eight real independently sourced datasets.
- Next video: a real Rio 2016 Olympics events dataset from a non-FiveThirtyEight real source, covering real events across twenty-eight real sports.
Practice on your own
- Merge the national prices onto
away_teaminstead ofhome_teamand recalculate the correlation. Compare it with 0.812 to see whether the home or away team matters more for price. - For each home team, average
matchup_avg_priceacross its home games and compare it with that team'snational_avg_price. Which teams charge noticeably more for divisional games? - Draw a scatter plot of
national_avg_priceagainstmatchup_avg_pricefrom the merged table and colour the points byconference.
The next lesson in the series moves to a real Rio 2016 Olympics events dataset from a non-FiveThirtyEight source, covering events across twenty-eight sports. Watch the video walkthrough of this lesson if any step felt unclear.
Found this useful?
All lessons, notebooks and datasets here are free. If they helped you, a coffee keeps new lessons coming.



