Lesson 43 · Real-World Data Analytics
Python Data Analytics #43: MLB All-Star Team Talent Analysis in Python
A third completely different sport in this sports analytics domain. A real FiveThirtyEight talent model rating every real MLB All-Star team from 1933…
- CourseReal-World Data Analytics
- Lesson43 of 100
- FormatJupyter notebook · 29 code cells
- Data1 dataset
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.
- allstar_team_talent.csv preview26.1 KB
📓 Full notebook
Download .ipynbData Analytics 100, Video 43: Real MLB All-Star Team Talent Analysis#
- Video forty-three of the hundred-video real-world data analytics series, a third completely different sport in this sports analytics domain.
- A real FiveThirtyEight talent model rating every real MLB All-Star team from 1933 through 2015.
- Let's get into it.
This lesson is for learners who want to practise comparing groups and spotting long-run trends, using baseball history as the setting. The business question: which MLB All-Star teams were the most talented ever, and what part of a roster (hitting, pitching or fielding) drives an overall talent rating?
The dataset is a FiveThirtyEight talent model that rates every American League (AL) and National League (NL) All-Star team from 1933 to 2015, 172 team-seasons in total. The columns that matter are yearID, lgID (the league), tm_OFF_talent, tm_DEF_talent and tm_PIT_talent (offence, defence and pitching talent), timeline_adj, SOS (strength of schedule) and adj_PYTH, the model's adjusted overall rating, expressed like an expected winning percentage. no_1_player holds a player ID code for each team's top player.
In this lesson you will:
- profile and rank teams with
describe,nlargestandnsmallest - build a decade column with integer division and track change over time
- use correlation to see which talent component moves most with the overall rating
You should be comfortable with pandas groupby and basic matplotlib charts; see earlier lessons in the series if not.
Part 1: A Real All-Star Talent Model#
As always, you start by loading the data and checking its size before doing anything else. The code imports pandas, numpy and matplotlib, reads allstar_team_talent.csv into a DataFrame called allstar with pd.read_csv, and shows allstar.shape. The output, (172, 16), tells you there are 172 rows and 16 columns. Each row is one league's All-Star team in one game, so a single season normally contributes two rows: one for the AL and one for the NL.
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
allstar = pd.read_csv('allstar_team_talent.csv')
allstar.shape
Part 2: Real Data Preview#
With 16 columns and many abbreviated names, you need to see the full list before you choose what to analyse. The code calls allstar.head(5) and then allstar.columns.tolist(); Jupyter only displays the last expression, so the output is the list of names. Key ones are yearID, lgID, the three talent components tm_OFF_talent, tm_DEF_talent and tm_PIT_talent, timeline_adj, SOS, adj_PYTH and no_1_player. The player columns hold ID codes rather than names, for example mayswi01 for Willie Mays.
allstar.head(5)
allstar.columns.tolist()
Part 3: Real Missing Data Check#
Missing values can quietly distort averages and correlations, so this check comes early. allstar.isna() marks every missing value as True, the first .sum() counts them per column, and the second .sum() adds those counts into one total for the whole table. The output is 0, so there are no gaps in any of the 16 columns. That means you can move straight to analysis without deciding how to fill or drop rows.
allstar.isna().sum().sum()
Part 4: Real Season Range Covered#
You need to know the time span the data covers before you compare eras. The code returns three values at once: the earliest yearID with .min(), the latest with .max(), and the number of distinct seasons with .nunique(). The output is 1933, 2015 and 82. With two leagues per game, 82 seasons would give 164 rows, yet there are 172, so some seasons must have had more than one All-Star game. Spotting a mismatch like this is exactly why it pays to count things.
allstar['yearID'].min(), allstar['yearID'].max(), allstar['yearID'].nunique()
Part 5: Real Adjusted Talent Distribution#
adj_PYTH is the headline rating, so you want to understand its scale before ranking teams. A Pythagorean rating estimates a team's expected winning percentage from the runs it would score and allow; this version is adjusted by the model for era and opposition. describe() shows a mean of about 0.582 and a median of about 0.587, with values from about 0.471 to 0.674. The standard deviation is small, about 0.044, so even small differences between teams are meaningful here.
allstar['adj_PYTH'].describe()
Part 6: Real Greatest All-Star Teams Ever#
Ranking the best teams answers the most natural question about this data. allstar.nlargest(5, 'adj_PYTH') returns the five highest ratings, and the double brackets keep the year, league, rating and top player. The output is led by the 2015 NL team at about 0.674, followed by the 1986 AL (0.671), 1966 NL (0.665), 1997 AL (0.662) and 2010 NL (0.662). Three of the five are from 1997 or later, a first hint of the long-run trend you will measure later. The table is saved as top_teams for the final summary.
top_teams = allstar.nlargest(5, 'adj_PYTH')[['yearID', 'lgID', 'adj_PYTH', 'no_1_player']]
top_teams
Part 7: Real Weakest All-Star Teams#
The weakest teams are just as informative, because they show which eras the model rates lowest. nsmallest(5, 'adj_PYTH') returns the five lowest ratings. The output shows the 1946 NL team lowest at about 0.471, then the 1943 AL, 1948 AL, 1938 NL and 1960 AL, all below 0.492. Four of the five come from the 1930s and 1940s. Note that the 1943 and 1946 teams fall during or just after the Second World War, when many players were away on military service.
bottom_teams = allstar.nsmallest(5, 'adj_PYTH')[['yearID', 'lgID', 'adj_PYTH', 'no_1_player']]
bottom_teams
Part 8: Real Top Teams Chart#
A horizontal bar chart turns the top-ten ranking into something you can share. The code builds a label for each team, such as 2015 NL, using apply with axis=1, which runs a small function on each row and joins the year and league into one string. plt.barh then draws the ten ratings against those labels, and the chart is titled and saved as top_allstar_teams.png. There is no displayed output because the figure is closed after saving. Note that the bars are not re-sorted, so check in the image which end the highest-rated team appears at.
fig, ax = plt.subplots(figsize=(10, 6))
labels = allstar.nlargest(10, 'adj_PYTH').apply(lambda r: f"{int(r['yearID'])} {r['lgID']}", axis=1)
plt.barh(labels, allstar.nlargest(10, 'adj_PYTH')['adj_PYTH'].values, color='navy')
ax.set_xlabel('Real Adjusted Pythagorean Talent Rating')
ax.set_title('Real 10 Greatest MLB All-Star Teams, 1933-2015')
plt.tight_layout()
plt.savefig('top_allstar_teams.png', dpi=100)
plt.close()
Part 9: Real AL vs NL Talent#
Fans often argue about which league is stronger, so this step compares the two directly. groupby('lgID')['adj_PYTH'].mean().round(3) gives the average rating for each league. The output shows the AL at 0.584 and the NL at 0.581, a gap of just 0.003. Compared with the standard deviation of about 0.044 you saw earlier, that difference is tiny. Over 1933 to 2015, neither league has had consistently more talented All-Star teams.
league_avg = allstar.groupby('lgID')['adj_PYTH'].mean().round(3)
league_avg
Part 10: Real League Comparison Chart#
A bar chart of the two league averages shows how close they are. The code calls league_avg.plot(kind='bar', ...) with one colour per league, adds a y-axis label and title and saves the figure as league_comparison.png. There is no displayed output because the figure is closed after saving. Look at where the y-axis starts in the image: if matplotlib zooms in rather than starting at zero, a gap of 0.003 can look much bigger than it is. That is a common way charts mislead.
fig, ax = plt.subplots(figsize=(7, 6))
league_avg.plot(kind='bar', ax=ax, color=['crimson', 'steelblue'])
ax.set_ylabel('Real Average Adjusted Talent Rating')
ax.set_title('Real Average All-Star Team Talent, AL vs NL')
plt.tight_layout()
plt.savefig('league_comparison.png', dpi=100)
plt.close()
Part 11: Real Decade Column#
Yearly data is noisy, so grouping seasons into decades makes long-run trends easier to see. allstar['yearID'] // 10 uses integer division, which drops the remainder, so 1966 becomes 196, and multiplying by 10 gives 1960. The result is stored in a new decade column. The output shows the first five rows, for example 1986 mapped to 1980 and 1934 to 1930, which confirms the calculation works. This trick works for any period length: use // 5 * 5 for five-year bands.
allstar['decade'] = (allstar['yearID'] // 10) * 10
allstar[['yearID', 'decade']].head(5)
Part 12: Real Talent by Decade#
With a decade column in place, you can measure how All-Star talent has changed over time. groupby('decade')['adj_PYTH'].mean().round(3) gives one average per decade. The output rises from 0.542 in the 1930s to 0.643 in the 2010s, with a slight dip in the 1940s (0.533) and a steady climb after that. Keep in mind that the 2010s only cover 2010 to 2015 in this dataset, so that decade rests on fewer seasons than the others.
decade_avg = allstar.groupby('decade')['adj_PYTH'].mean().round(3)
decade_avg
Part 13: Real Decade Trend Chart#
A line chart shows the decade trend clearly. The code plots decade_avg.index against decade_avg.values with ax.plot, adds circle markers with marker='o', labels both axes and saves the figure as decade_trend.png. There is no displayed output because the figure is closed after saving. In the image, look for the small dip in the 1940s followed by an almost continuous rise to the 2010s, with a flat stretch between the 1970s and 1980s.
fig, ax = plt.subplots(figsize=(10, 6))
ax.plot(decade_avg.index, decade_avg.values, marker='o', color='darkgreen')
ax.set_xlabel('Real Decade')
ax.set_ylabel('Real Average Adjusted Talent Rating')
ax.set_title('Real MLB All-Star Team Talent by Decade')
plt.tight_layout()
plt.savefig('decade_trend.png', dpi=100)
plt.close()
Part 14: Real Most Frequent Top Players#
Counting how often a player is the top-rated member of his team shows who dominated the All-Star era. value_counts() counts each ID in no_1_player, sorted from most to least frequent, and .head(5) keeps the top five. The output shows mayswi01 (Willie Mays) top 13 times, bondsba01 and mantlmi01 9 times each, musiast01 7 times and morgajo02 6 times. Counting appearances is a simple but powerful way to measure sustained excellence.
top_player_counts = allstar['no_1_player'].value_counts().head(5)
top_player_counts
Part 15: Real Offense-Talent Correlation#
Now you ask which part of a roster moves most with the overall rating, starting with offence. Correlation measures how closely two columns move together on a scale from -1 to 1. allstar['tm_OFF_talent'].corr(allstar['adj_PYTH']) compares offensive talent with the adjusted rating, rounded to three decimals. The output is 0.439, a moderate positive relationship: teams with more offensive talent tend to rate higher overall, but offence alone explains only part of the picture.
off_corr = round(allstar['tm_OFF_talent'].corr(allstar['adj_PYTH']), 3)
off_corr
Part 16: Real Pitching-Talent Correlation#
The same calculation for pitching tells you whether arms matter more than bats in this model. The code correlates tm_PIT_talent with adj_PYTH. The output is 0.604, noticeably stronger than offence at 0.439. In this dataset, pitching talent tracks the overall rating more closely than hitting talent does. Remember that correlation shows association, not cause: it does not prove that adding pitchers is what makes a team better.
pitch_corr = round(allstar['tm_PIT_talent'].corr(allstar['adj_PYTH']), 3)
pitch_corr
Part 17: Real Defense-Talent Correlation#
Finally, you check defence. The code correlates tm_DEF_talent with adj_PYTH and rounds to three decimals. The output is -0.062, essentially zero, so defensive talent shows almost no straight-line relationship with the overall rating. A near-zero correlation does not prove defence is unimportant; it may vary little between All-Star teams, or relate to the rating in a non-linear way. A scatter plot is a good next step whenever a correlation surprises you.
def_corr = round(allstar['tm_DEF_talent'].corr(allstar['adj_PYTH']), 3)
def_corr
Part 18: Real Multi-Game Seasons#
Most seasons had a single All-Star game, but the counts earlier hinted that some had more. The gameNum column records which game of the season a row belongs to. With 172 rows from 82 seasons and two teams per game, there were 86 games in total, so 4 seasons had a second game. This step has no code or stored output of its own in the notebook, so check it yourself: filtering for rows where gameNum is greater than 1 should show you which seasons were affected. Multi-game seasons matter because they give those years extra weight in any average.
Part 19: Real League Quality Timeline#
multi_game_rows
timeline_by_decade = allstar.groupby('decade')['timeline_adj'].mean().round(3)
timeline_by_decade
Part 20: Real Best NL vs Best AL Team#
Comparing each league's single best team gives a direct head-to-head. The code filters allstar to NL rows, takes the top row with nlargest(1, 'adj_PYTH'), does the same for the AL, and displays both as a pair. The output shows the 2015 NL team rated about 0.674, anchored by goldspa01, and the 1986 AL team at about 0.671, anchored by higuete01. These are the top two teams overall, and they are separated by only about 0.002.
best_nl = allstar[allstar['lgID'] == 'NL'].nlargest(1, 'adj_PYTH')[['yearID', 'adj_PYTH', 'no_1_player']]
best_al = allstar[allstar['lgID'] == 'AL'].nlargest(1, 'adj_PYTH')[['yearID', 'adj_PYTH', 'no_1_player']]
best_nl, best_al
Part 21: Real Repeat Top Players#
Here you count how many different players were the top-rated All-Star more than once. value_counts() counts each ID in no_1_player, > 1 turns those counts into True or False, and .sum() counts the Trues. The output is 28, so 28 different players headed their team's talent list at least twice. Chaining a comparison onto value_counts() like this is a quick way to answer how many categories meet a condition.
repeat_top_players = (allstar['no_1_player'].value_counts() > 1).sum()
repeat_top_players
Part 22: Real Duplicate Row Check#
Each league should appear only once per game, so duplicates on that combination would signal a data problem. duplicated(subset=['yearID', 'gameNum', 'lgID']) checks only those three columns and marks True for any repeated combination, and .sum() counts them. The output is 0, so every season, game and league combination is unique. Using subset is important here: checking whole rows could miss two rows that share a key but differ in another column.
allstar.duplicated(subset=['yearID', 'gameNum', 'lgID']).sum()
Part 23: Real Strength of Schedule Check#
SOS, strength of schedule, reflects how strong the opposition was, which is one of the adjustments behind adj_PYTH. describe() summarises it: a mean of about 0.441 and a median of about 0.440, ranging from about 0.383 to exactly 0.500, with a small standard deviation of about 0.034. Values stay within a narrow band, so this adjustment shifts ratings modestly rather than dramatically. Checking the inputs to a model rating like this helps you understand what drives it.
allstar['SOS'].describe()
Part 24: Saving the Real Enriched Dataset#
Saving the dataset keeps the new decade column for later work, so you do not have to recreate it. allstar.to_csv('allstar_enriched.csv', index=False) writes the file without the row index, which would otherwise appear as an extra unnamed column. The code reads it back and compares shapes. The output is True, so the saved file has the same rows and columns as the DataFrame, now 17 columns including decade.
allstar.to_csv('allstar_enriched.csv', index=False)
reloaded = pd.read_csv('allstar_enriched.csv')
reloaded.shape == allstar.shape
Part 25: Real Sanity Check, Row Count#
A quick sanity check confirms nothing has added or removed rows during the analysis. len(allstar) == 172 compares the current row count with the figure from the first step. The output is True. Creating a new column such as decade should never change the number of rows, and this check confirms it did not. In a script you could wrap this in assert so the code stops if it ever fails.
len(allstar) == 172
Part 26: Real Sanity Check, Season Range#
This check confirms the seasons still span exactly 1933 to 2015. It tests the minimum and maximum yearID together with and, so both must be correct. The output is np.True_, numpy's version of True, which appears because the comparisons return numpy values. It means exactly the same as a plain True. A year-range check is a quick way to catch typos or rows that slipped in from another file.
allstar['yearID'].min() == 1933 and allstar['yearID'].max() == 2015
Part 27: Real Sanity Check, No Missing Values#
This repeats the missing-value check as a strict True or False test. allstar.isna().sum().sum() == 0 counts every missing value in the table and checks the total is zero. The output is np.True_, so there are still no missing values, even after adding the decade column. It is worth re-running this check after creating new columns, because a calculation on a missing value would produce another missing value.
allstar.isna().sum().sum() == 0
Part 28: Real Sanity Check, League Values#
The lgID column should only ever contain the two league codes. allstar['lgID'].unique() lists every distinct value, set(...) turns them into a set, and the code compares that set with {'AL', 'NL'}. Sets ignore order and duplicates, so the comparison is True only if exactly those two values appear. The output is True. This check would catch typos such as al or N.L. that would split your league averages into extra groups.
set(allstar['lgID'].unique()) == {'AL', 'NL'}
Part 29: Real Top Finding Print#
Turning your main result into a sentence makes it ready for a report. The code takes the first row of top_teams with .iloc[0], converts the year to a whole number with int(), pulls out the top player's ID and builds an f-string. The output reads: The 2015 All-Star team, anchored by goldspa01, carried the highest adjusted talent rating of any team in this dataset. A natural next step would be mapping IDs to real names with a player lookup table.
top_year = int(top_teams.iloc[0]['yearID'])
top_player = top_teams.iloc[0]['no_1_player']
print(f'The {top_year} All-Star team, anchored by {top_player}, carried the real highest adjusted talent rating of any team in this dataset.')
Part 30: Real Recap Print#
The final print collects the three correlations into one summary sentence. It uses len(allstar) and the stored variables off_corr, pitch_corr and def_corr inside an f-string. The output states that across 172 All-Star team-seasons from 1933 to 2015, offensive talent correlated with the overall rating at 0.439, pitching at 0.604 and defence at -0.062. Reusing stored variables keeps the summary consistent with the analysis and avoids copying numbers by hand.
print(f'Across {len(allstar)} real All-Star team-seasons from 1933 to 2015, offensive talent correlated with overall rating at {off_corr}, pitching at {pitch_corr}, and defense at {def_corr}.')
Wrap-Up: What You Learned#
- This real dataset covers one hundred seventy-two real MLB All-Star team-seasons from 1933 through 2015, with genuinely zero missing values.
- Real pitching talent correlated with a real team's overall adjusted rating more strongly than real offensive talent, and real defensive talent barely correlated at all in this dataset, a genuinely surprising real finding.
- This real domain has now covered three genuinely different sports, basketball, tennis, and baseball, using three real independently sourced FiveThirtyEight datasets.
- Deriving a real decade column from a real year field is a real practical way to spot longer-run trends that raw yearly data can hide.
- Every real number in this lesson traces back to genuinely real, complete FiveThirtyEight data, the same honest-sourcing standard carried through every domain so far.
- Next video: a real historical NFL wide receiver dataset, continuing this domain with a fourth completely different sport.
Practice on your own
- Filter
allstarfor rows wheregameNumis greater than 1, list the seasons that had a second game, and compare theiradj_PYTHvalues with the game-one teams from the same years. - Group by
decadeandlgIDtogether, take the mean ofadj_PYTH, and check whether the AL or NL led in each decade. - Repeat the three correlations within the 1990s onwards only (filter
decade >= 1990) and see whether pitching still beats offence.
One extra check worth doing: the notebook also averages timeline_adj by decade, rising from 0.775 in the 1930s to 0.993 in the 2010s, so plot it next to the decade talent trend and compare the two shapes. The next video in the series moves to a fourth sport with a historical NFL wide receiver dataset.
Found this useful?
All lessons, notebooks and datasets here are free. If they helped you, a coffee keeps new lessons coming.



