Lesson 50 · Real-World Data Analytics
Data Quality Tables for Many Datasets: Sports Analytics Capstone | Python Data Analytics #50
And the real capstone closing out the Sports Analytics domain. Reloading all nine real datasets from this domain, basketball, tennis, baseball twice,…
- CourseReal-World Data Analytics
- Lesson50 of 100
- Video18 min
- FormatJupyter notebook · 30 code cells
- Data9 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.
- nba_draft_projections_raw.csv preview59.1 KB
- players_time.csv preview4.4 KB
- allstar_team_talent.csv preview26.1 KB
- wr_advanced_historical.csv preview60.3 KB
- fifa_countries_audience.csv preview5.0 KB
- chess_transfers.csv preview60.8 KB
- foul_balls.csv preview54.7 KB
- national_average.csv preview944 B
- rio2016_events.csv preview21.0 KB
📓 Full notebook
Download .ipynbData Analytics 100, Video 50: Real Sports Analytics Domain Capstone#
- Video fifty of the hundred-video real-world data analytics series, and the real capstone closing out the Sports Analytics domain.
- Reloading all nine real datasets from this domain, basketball, tennis, baseball twice, football twice, soccer, chess, and the Rio Olympics, to build one real cross-domain summary.
- Let's get into it.
This capstone is for learners who have worked through the Sports Analytics lessons, videos 41 to 49, and want to practise pulling results from several unrelated datasets into one summary. The question is a reporting one: if a manager asked for a one-page overview of everything this domain found, how would you build it reliably? The notebook reloads all nine sports datasets used so far, from the NBA draft projections and ATP tennis timings to the FIDE chess transfers, MLB foul balls, NFL ticket prices and Rio 2016 events, and recomputes one headline finding from each. Because these datasets share no common key, such as a player or team ID, they cannot be merged. Instead, you build a small summary table with one row per lesson.
In this lesson you will:
- reload several files and keep track of their sizes
- recompute headline results from source rather than copying them from memory
- assemble a summary DataFrame from a dictionary of lists and f-strings
- compare correlations from different datasets side by side
Prerequisites: you should have completed, or at least skimmed, videos 41 to 49, and be comfortable with sort_values, iloc and f-strings.
Part 1: Real NBA Draft Data Reload#
A capstone summary is only trustworthy if every number is recalculated from the original file, so you start by reloading each dataset. The code imports pandas, numpy and matplotlib, reads the NBA draft projections file into nba and checks .shape. The output is (642, 9): 642 rows and nine columns. Recording each shape as you load gives you a quick check that you have the same files as in the original lesson.
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
nba = pd.read_csv('nba_draft_projections_raw.csv')
nba.shape
Part 2: Real ATP Tennis Data Reload#
The tennis dataset from video 42 is the next to reload. The code reads players_time.csv into tennis and checks its shape. The output is (218, 2), so the file holds 218 players with just two columns: a player name and the extra seconds each player adds per point. Small, narrow tables like this are quick to summarise, but always confirm the column names before you sort by them.
tennis = pd.read_csv('players_time.csv')
tennis.shape
Part 3: Real MLB All-Star Data Reload#
Next comes the MLB All-Star dataset from video 43. The code reads allstar_team_talent.csv into allstar and checks its shape. The output is (172, 16): 172 rows and 16 columns, the widest file in this domain. Two of those columns, the team pitching and offensive talent scores, are used later to recompute that lesson's correlation finding.
allstar = pd.read_csv('allstar_team_talent.csv')
allstar.shape
Part 4: Real NFL Wide Receiver Data Reload#
The NFL wide receiver dataset from video 44 is reloaded into wr. The output of .shape is (961, 6), so it has 961 rows and six columns. That turns out to be the largest dataset in the domain, a fact the final summary confirms. Larger files are not always more useful, but knowing the size of each source helps you judge how much weight its headline finding can carry.
wr = pd.read_csv('wr_advanced_historical.csv')
wr.shape
Part 5: Real FIFA Soccer Data Reload#
The FIFA dataset from video 45 is reloaded into fifa. The output is (191, 5): 191 countries described by five columns. Two of these, population_share and tv_audience_share, are used in this capstone, one for the headline and both for the correlation comparison near the end. Consistent variable names like fifa and chess make a notebook with nine datasets much easier to follow.
fifa = pd.read_csv('fifa_countries_audience.csv')
fifa.shape
Part 6: Real FIDE Chess Data Reload#
The chess transfer dataset from video 46 is reloaded into chess. The shape is (829, 5), exactly as in the original lesson: 829 federation transfers and five columns. Matching the earlier shape is a simple but useful confirmation that you are working from the same file and that nothing has changed since that analysis.
chess = pd.read_csv('chess_transfers.csv')
chess.shape
Part 7: Real MLB Foul Ball Data Reload#
The foul ball dataset from video 47 is reloaded into foul. The output is (905, 7), matching the 905 tracked foul balls and seven columns from that lesson. Remember that exit_velocity had many missing values there; the headline step here uses nlargest, which skips missing values, so those gaps do not cause problems.
foul = pd.read_csv('foul_balls.csv')
foul.shape
Part 8: Real NFL Ticket Data Reload#
The NFL ticket dataset from video 48 needs one small fix as it loads. The code reads national_average.csv and immediately renames its two awkward columns to team_raw and national_avg_price by assigning a list to national.columns. The shape is (32, 2), one row per NFL team. The trailing word 'Tickets' in team names is not removed this time, which is why it appears in the capstone table later.
national = pd.read_csv('national_average.csv')
national.columns = ['team_raw', 'national_avg_price']
national.shape
Part 9: Real Rio 2016 Data Reload#
The last reload is the Rio 2016 events data from video 49, stored in rio. The output is (306, 6): 306 events and six columns. With all nine datasets now in memory, each under a clear variable name, the remaining steps can compute totals and headlines across them without reading any file twice.
rio = pd.read_csv('rio2016_events.csv')
rio.shape
Part 10: Real Total Rows Across the Domain#
A total row count gives a sense of how much real data the domain has covered. The code adds the first element of each DataFrame's .shape, which is its row count, across all nine datasets. The output is 4256 rows in total. Storing this in total_rows matters, because a later check confirms that the capstone table's row counts add up to the same figure.
total_rows = nba.shape[0] + tennis.shape[0] + allstar.shape[0] + wr.shape[0] + fifa.shape[0] + chess.shape[0] + foul.shape[0] + national.shape[0] + rio.shape[0]
total_rows
Part 11: Real NBA Draft Headline#
Each headline is recalculated from the data rather than copied from the earlier lesson. The code sorts nba by Projected SPM from highest to lowest and takes the first row with .iloc[0]. SPM is a statistical plus-minus measure, a single number estimating a player's overall impact. The output shows Anthony Davis, drafted in 2012, with the highest projected SPM of about 1.430. Selecting a few fields from the row with a list of names keeps the output readable.
top_nba = nba.sort_values('Projected SPM', ascending=False).iloc[0]
top_nba[['Player', 'Draft Year', 'Projected SPM']]
Part 12: Real ATP Tennis Headline#
The same sort-and-take-first pattern finds the tennis headline. Sorting tennis by seconds_added_per_point in descending order puts the slowest player first, the one who adds the most time between points. The output shows Emanuel Couto at 6.35 seconds added per point. If you wanted the fastest player instead, you would simply sort in ascending order, or use nsmallest.
slowest = tennis.sort_values('seconds_added_per_point', ascending=False).iloc[0]
slowest[['player', 'seconds_added_per_point']]
Part 13: Real MLB All-Star Headline#
For the All-Star lesson, the headline is a comparison of two correlations rather than a single name. .corr() computes the Pearson correlation, a number from -1 to 1 showing how closely two columns move together. The code correlates pitching talent and offensive talent each with adj_PYTH, an adjusted measure of team strength. The output is (0.604, 0.439): pitching talent has the stronger link with team strength. Rounding to three decimals keeps the numbers readable in the summary.
pitch_corr = round(allstar['tm_PIT_talent'].corr(allstar['adj_PYTH']), 3)
off_corr = round(allstar['tm_OFF_talent'].corr(allstar['adj_PYTH']), 3)
pitch_corr, off_corr
Part 14: Real NFL Wide Receiver Headline#
The wide receiver headline uses the sort-and-take-first pattern again. Sorting wr by career_try in descending order puts the player with the highest career TRY first; TRY is the receiving yards metric used in video 44. The output shows Tim Brown with a career TRY of about 14,181. Very precise decimals like 14181.02885 are rounded to one decimal later when the value goes into the summary table.
top_wr = wr.sort_values('career_try', ascending=False).iloc[0]
top_wr[['player_name', 'career_try']]
Part 15: Real FIFA Soccer Headline#
The FIFA headline identifies the country with the biggest share of the World Cup television audience. Sorting fifa by tv_audience_share and taking the first row returns China, with a 14.8% share. Because each headline is computed in its own step and stored in a variable, any of them can be updated independently if you later find a better way to summarise that lesson.
top_fifa = fifa.sort_values('tv_audience_share', ascending=False).iloc[0]
top_fifa[['country', 'tv_audience_share']]
Part 16: Real FIDE Chess Headline#
The chess headline uses value_counts() instead of sorting the table. Counting the Federation column gives incoming transfers per federation, already sorted from most to least. .index[0] returns the top federation's name and .iloc[0] its count, and the output is ('USA', 82). This is the same result as in video 46, which confirms the reloaded data matches.
fed_counts = chess['Federation'].value_counts()
fed_counts.index[0], fed_counts.iloc[0]
Part 17: Real MLB Foul Ball Headline#
For the foul ball dataset, the headline is the fastest recorded ball. nlargest(1, 'exit_velocity') returns the single fastest row and .iloc[0] turns it into a Series. The output shows a speed of 110.6 mph landing in zone 4. nlargest ignores missing speeds automatically, which matters here because about a third of balls in this file have no recorded speed.
fastest_foul = foul.nlargest(1, 'exit_velocity').iloc[0]
fastest_foul[['exit_velocity', 'used_zone']]
Part 18: Real NFL Ticket Headline#
The NFL ticket headline is the most expensive team on average. Sorting national by national_avg_price in descending order and taking the first row returns the Seattle Seahawks at $291. The team name still carries the word 'Tickets' because the cleanup from video 48 was not repeated. If you were preparing this for a report, you would add the str.replace step from that lesson.
top_team = national.sort_values('national_avg_price', ascending=False).iloc[0]
top_team[['team_raw', 'national_avg_price']]
Part 19: Real Rio 2016 Headline#
The Rio 2016 headline comes from counting events per sport. value_counts() on sport sorts the counts, and the first entry is returned by name and value. The output is ('athletics', 47), so athletics had the most events at the Games. The lower-case name is capitalised with .title() when it is added to the capstone table.
sport_counts = rio['sport'].value_counts()
sport_counts.index[0], sport_counts.iloc[0]
Part 20: Building the Real Domain Capstone Table#
With every headline computed, you can collect them into one table. The code builds a DataFrame from a dictionary in which each key is a column and each value is a list of nine items, one per lesson. dataset_rows uses each DataFrame's row count, and headline_finding uses f-strings with format codes such as :.3f (three decimals) and :.0f (no decimals) to turn each result into short text. There is no output because the table is only created here. Keep all lists the same length, or pandas raises an error.
capstone = pd.DataFrame({
'video': [41, 42, 43, 44, 45, 46, 47, 48, 49],
'sport': ['Basketball', 'Tennis', 'Baseball', 'Football', 'Soccer', 'Chess', 'Baseball', 'Football', 'Multi-Sport'],
'dataset_rows': [nba.shape[0], tennis.shape[0], allstar.shape[0], wr.shape[0], fifa.shape[0], chess.shape[0], foul.shape[0], national.shape[0], rio.shape[0]],
'headline_finding': [f'{top_nba["Player"]}, {top_nba["Projected SPM"]:.3f} SPM', f'{slowest["player"]}, {slowest["seconds_added_per_point"]:.2f} sec/pt', f'Pitch corr {pitch_corr} vs off corr {off_corr}', f'{top_wr["player_name"]}, {top_wr["career_try"]:.1f} TRY', f'{top_fifa["country"]}, {top_fifa["tv_audience_share"]}% TV share', f'{fed_counts.index[0]}, {fed_counts.iloc[0]} incoming', f'{fastest_foul["exit_velocity"]} mph, zone {fastest_foul["used_zone"]:.0f}', f'{top_team["team_raw"]}, ${top_team["national_avg_price"]}', f'{sport_counts.index[0].title()}, {sport_counts.iloc[0]} events'],
})
Part 21: Real Capstone Table Preview#
Displaying the table lets you check every row before you rely on it. The output shows nine rows, videos 41 to 49, with each sport, its dataset size and a short headline, such as 'Anthony Davis, 1.430 SPM', 'USA, 82 incoming' and 'Athletics, 47 events'. Scan it for formatting problems: the NFL row reads 'Seattle Seahawks Tickets, $291', a leftover from the uncleaned team name. Reviewing the final table like this is the easiest way to catch small presentation issues.
capstone
Part 22: Real Total Domain Row Count Check#
This check confirms that the capstone table and the earlier total agree. The code sums the dataset_rows column and compares it with total_rows. The output np.True_ shows they match at 4256. Because the two figures were computed separately, a match is good evidence that no dataset was missed or entered twice when building the table.
capstone['dataset_rows'].sum() == total_rows
Part 23: Real Sport Variety Count#
Counting distinct sports shows how varied the domain was. nunique() on the sport column returns 7, not 9, because baseball and football each appear twice in the table, in videos 43 and 47 and in videos 44 and 48. Note that 'Multi-Sport' for the Olympics counts as one of the seven. Always check whether a category label is reused before quoting a count of distinct values.
capstone['sport'].nunique()
Part 24: Real Dataset Size by Lesson Chart#
A bar chart of dataset sizes shows at a glance how much each lesson worked with. The code uses ax.bar with the video numbers converted to text via astype(str), so they are treated as labels rather than a numeric scale, and the row counts as bar heights. The chart is saved to domain_dataset_sizes.png and closed, so it does not display in the notebook. Look for the tall bars for videos 44, 46 and 47 and the very short bar for video 48.
fig, ax = plt.subplots(figsize=(10, 6))
ax.bar(capstone['video'].astype(str), capstone['dataset_rows'], color='teal')
ax.set_xlabel('Real Video Number')
ax.set_ylabel('Real Dataset Row Count')
ax.set_title('Real Dataset Size Across the Sports Analytics Domain')
plt.tight_layout()
plt.savefig('domain_dataset_sizes.png', dpi=100)
plt.close()
Part 25: Real Cross-Domain Correlation Comparison#
Putting correlations from different lessons side by side shows which relationships were strongest. The code computes the FIFA correlation between population_share and tv_audience_share, stores it in a variable named gdp_corr even though it uses population, and types the NFL figure in by hand as 0.812. The output shows MLB pitch talent vs strength at 0.604, FIFA population vs audience at 0.731 and NFL team vs game price at 0.812. Note that the NFL value is hard-coded rather than recomputed, so it would not update if the data changed.
gdp_corr = round(fifa['population_share'].corr(fifa['tv_audience_share']), 3)
price_corr_note = 0.812
pd.Series({'MLB pitch talent vs strength': pitch_corr, 'FIFA population vs audience': gdp_corr, 'NFL team price vs game price': price_corr_note})
Part 26: Real Average Dataset Size#
An average dataset size is a simple descriptive summary of the domain. .mean() on dataset_rows gives the arithmetic mean, rounded to one decimal, and the output is 472.9 rows. That equals 4256 divided by 9. With sizes ranging from 32 to 961 rows, the average hides a lot of variation, so it is worth quoting the range alongside it.
avg_rows = round(capstone['dataset_rows'].mean(), 1)
avg_rows
Part 27: Saving the Real Domain Capstone Summary#
Saving the capstone table gives you a single file that summarises the whole domain. to_csv writes it to sports_domain_capstone_summary.csv with index=False, so the row numbers are not saved as an extra column. The code reads it back and compares shapes, and the output True confirms the file holds the same nine rows and four columns. This file is easy to share with someone who does not use Python.
capstone.to_csv('sports_domain_capstone_summary.csv', index=False)
reloaded = pd.read_csv('sports_domain_capstone_summary.csv')
reloaded.shape == capstone.shape
Part 28: Real Sanity Check, Nine Lessons#
The last sanity check confirms the summary has one row for each of the nine lessons. len(capstone) == 9 returns True. If a lesson were added or removed from the lists in the dictionary, pandas would raise an error for mismatched lengths, but this check also guards against someone later appending rows to the table.
len(capstone) == 9
Part 29: Real Top Finding Print#
This step reports which lesson used the largest dataset. idxmax() returns the index label of the largest dataset_rows value, and .loc fetches that full row. The printed output says the largest dataset came from video 44, the Football dataset, with 961 rows. Building the sentence from the row's values means it stays correct if dataset sizes change.
biggest_dataset = capstone.loc[capstone['dataset_rows'].idxmax()]
print(f'The real largest dataset in this domain came from video {biggest_dataset["video"]}, the real {biggest_dataset["sport"]} dataset, with {biggest_dataset["dataset_rows"]} real rows.')
Part 30: Real Domain Recap Print#
The final recap summarises the entire domain in one sentence. The f-string combines total_rows with the count of distinct sports from the capstone table. The printed output says that across nine lessons and 4256 total rows, the domain covered 7 different sports, from an NBA draft board to an Olympic events schedule. A one-sentence summary like this is often what a busy reader remembers, so make sure every number in it comes from a variable.
print(f'Across nine real lessons and {total_rows} real total rows, this domain covered {capstone["sport"].nunique()} genuinely different sports, from a real NBA draft board to a real Olympic events schedule, without fabricating a single real number.')
Wrap-Up: What You Learned#
- This real capstone reloaded all nine real datasets from the Sports Analytics domain and recomputed every real headline finding fresh, rather than trusting typed-out memory.
- Because players, teams, countries, and federations share no real common join key, this capstone honestly built one real summary row per lesson instead of forcing an artificial merge.
- Real dataset sizes across this domain ranged from thirty-two real NFL teams to nine hundred sixty-one real historical wide receivers, and every real number traced back to a genuinely real, independently sourced dataset.
- This closes out Domain 5 of the Analytics 100 series, ten real lessons built on nine real independently sourced sports datasets, zero fabricated numbers anywhere.
- Next video: the start of Domain 6, real Climate and Environment analytics.
Practice on your own
- Add a
dataset_columnscolumn to the capstone table usingshape[1]for each dataset, then find which lesson had the widest and the narrowest data. - Replace the hard-coded NFL correlation of 0.812 with a recomputed one: reload
2014_average_ticket_price.csv, repeat the home team extraction and merge from video 48, and check that you get the same value. - Clean the NFL headline by removing ' Tickets' from
team_rawbefore building the table, then add a second headline column for each lesson using the lowest or smallest result instead of the highest.
The next video starts Domain 6 of the series, which moves to real Climate and Environment analytics. Watch the video walkthrough of this capstone 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.



