Mathew K Analytics

Lesson 47 · Real-World Data Analytics

True vs Fake Duplicates in Pandas: Baseball Foul Ball Data | Python Data Analytics #47

Returning to baseball with a completely different, fan-safety angle. A real FiveThirtyEight dataset of nine hundred five real foul balls tracked at the ten…

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 .ipynb

Data Analytics 100, Video 47: Real MLB Foul Ball Safety Analysis#

  • Video forty-seven of the hundred-video real-world data analytics series, returning to baseball with a completely different, fan-safety angle.
  • A real FiveThirtyEight dataset of nine hundred five real foul balls tracked at the ten most foul-heavy stadiums in 2019.
  • Let's get into it.

This lesson is for learners who already know how to load and summarise a DataFrame and want to practise asking a safety-focused question of real data. The question is: where do foul balls land in the stands, how hard are they hit, and how reliable is a method that predicts the landing spot without video? The dataset comes from FiveThirtyEight and covers foul balls tracked at the ten most foul-heavy MLB stadiums in 2019. The columns that matter are matchup (the game), type_of_hit (fly, ground, line and so on), exit_velocity (how fast the ball left the bat, in miles per hour), predicted_zone, camera_zone and used_zone (the landing zone used for analysis).

In this lesson you will:

  • audit missing values and decide what they mean
  • break foul balls down by hit type, landing zone and stadium
  • compare average speeds across groups with groupby
  • measure how often a predicted zone agrees with camera footage
  • flag high-speed fouls as a new column

Prerequisites: you should be comfortable with value_counts(), groupby and boolean masks. Earlier lessons in the series cover these if you need a refresher.

Part 1: A Real Foul Ball Safety Dataset#

Every analysis starts by confirming what you have loaded. The code imports pandas, numpy and matplotlib, reads foul_balls.csv into a DataFrame called fouls and checks .shape, which returns (rows, columns). The output is (905, 7): 905 tracked foul balls described by seven columns. That matches the 905 balls described in the lesson introduction, which is a quick first sign the file loaded completely. Keep this number in mind, because a sanity check at the end tests it again.

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
fouls = pd.read_csv('foul_balls.csv')
fouls.shape
(905, 7)

Part 2: Real Data Preview#

Exact column names matter because every later step refers to them. The code runs fouls.head(5) and then fouls.columns.tolist(), but Jupyter only displays the last expression, so the output is just the list of seven names. Three of them describe the landing zone in different ways: predicted_zone (estimated without video), camera_zone (confirmed from footage) and used_zone (the value used for analysis). Understanding why there are three versions of the same idea is the key to the prediction accuracy test later. Run head(5) on its own if you want to see sample rows.

fouls.head(5)
fouls.columns.tolist()
['matchup',
 'game_date',
 'type_of_hit',
 'exit_velocity',
 'predicted_zone',
 'camera_zone',
 'used_zone']

Part 3: Real Missing Data Check#

Missing values tell you which questions the data can and cannot answer. fouls.isna() marks each empty cell as True, and .sum() counts them per column. The output shows two incomplete columns: exit_velocity is missing for 326 balls and camera_zone for 512. Every other column is complete, including used_zone, so you can analyse landing zones for all 905 balls. Any average speed you calculate, however, will be based only on the balls where speed was recorded, which is worth stating whenever you quote it.

fouls.isna().sum()
matchup             0
game_date           0
type_of_hit         0
exit_velocity     326
predicted_zone      0
camera_zone       512
used_zone           0
dtype: int64

Part 4: Real Stadiums Covered#

Before comparing stadiums you need to know how the balls are spread across games. The code calls nunique() and then value_counts() on matchup; only the last result is displayed, which lists ten matchups with their counts. Baltimore Orioles vs Minnesota Twins has the most tracked fouls with 113, and New York Yankees vs Baltimore Orioles the fewest with 66. The spread is fairly even, so no single game dominates the data. Notice the inconsistent spelling of 'VS' and 'vs' in the names, a small reminder that real text data is rarely perfectly tidy.

fouls['matchup'].nunique()
fouls['matchup'].value_counts()
matchup
Baltimore Orioles VS Minnesota Twins            113
Pittsburgh Pirates VS Milwaukee Brewers         111
Oakland A's vs Houston Astros                   109
Seattle Mariners VS Minnesota Twins             100
Texas Rangers vs Toronto Blue Jays               87
Los Angeles Dodgers vs Arizona Diamondsbacks     86
Milwaukee Brewers vs New York Mets               85
Philadelphia Phillies vs Miami Marlins           75
Atlanta Braves vs New York Mets                  73
New York Yankees vs Baltimore Orioles            66
Name: count, dtype: int64

Part 5: Real Type of Hit Breakdown#

The type of hit shapes where a ball goes and how dangerous it is, so it is worth counting first. value_counts() on type_of_hit counts each category and sorts from most to least common. Fly balls lead with 521, followed by ground balls with 226, line drives with 87, pop ups with 54 and 17 cases where the batter hit himself. Fly balls alone account for more than half of all tracked fouls. These categories are reused later to compare speeds, so check their exact spelling, including capital letters, here.

fouls['type_of_hit'].value_counts()
type_of_hit
Fly                 521
Ground              226
Line                 87
Pop Up               54
Batter hits self     17
Name: count, dtype: int64

Part 6: Real Landing Zone Breakdown#

Landing zones are the heart of a fan safety question, because they show where in the stands balls arrive. value_counts() counts balls per zone and .sort_index() orders the result by zone number rather than by count, which keeps the zones in their natural order. Zone 1 receives the most with 278, then zone 5 with 226 and zone 4 with 214, while zones 6 and 7 receive only 6 and 5. The notebook does not describe each zone's physical location, so check the original FiveThirtyEight write-up before drawing conclusions about specific seats.

fouls['used_zone'].value_counts().sort_index()
used_zone
1    278
2     96
3     80
4    214
5    226
6      6
7      5
Name: count, dtype: int64

Part 7: Real Landing Zone Chart#

A bar chart makes the uneven spread across zones obvious. The code reuses the sorted zone counts and draws vertical bars with kind='bar', keeping the zones in numeric order along the x-axis. It adds labels and a title, saves the chart to landing_zones.png and calls plt.close(), so nothing displays in the notebook itself. When you open the image, look for the tall bar at zone 1, the two similar bars at zones 4 and 5, and the almost empty zones 6 and 7.

fig, ax = plt.subplots(figsize=(8, 6))
fouls['used_zone'].value_counts().sort_index().plot(kind='bar', ax=ax, color='steelblue')
ax.set_xlabel('Real Landing Zone')
ax.set_ylabel('Real Number of Foul Balls')
ax.set_title('Real Foul Ball Landing Zones Across 10 Stadiums, 2019')
plt.tight_layout()
plt.savefig('landing_zones.png', dpi=100)
plt.close()

Part 8: Real Exit Velocity Distribution#

Speed is what turns a foul ball into an injury risk, so you need a feel for its typical range. describe() gives a summary of a numeric column: count, mean, standard deviation (how spread out values are), minimum, quartiles and maximum. Only 579 balls have a recorded speed. The mean is about 76.4 mph and the median (the 50% value) about 75.7 mph, so the distribution is fairly balanced. The middle half of balls sits between 69.7 and 81.7 mph, but the fastest reaches 110.6 mph and the slowest 25.4 mph.

fouls['exit_velocity'].describe()
count    579.000000
mean      76.383938
std       12.046806
min       25.400000
25%       69.700000
50%       75.700000
75%       81.700000
max      110.600000
Name: exit_velocity, dtype: float64

Part 9: Real Fastest Foul Balls#

The fastest balls are the ones most likely to hurt someone, so it helps to look at them individually. nlargest(5, 'exit_velocity') returns the five rows with the highest speed, and the double-bracket selection keeps only four useful columns. The output shows a line drive at 110.6 mph landing in zone 4 at the top, followed by fly balls at 108.7 and two at 108.5 mph. Three of the five come from the Orioles vs Twins game. Unlike sorting the whole table, nlargest is a direct way to get a top-N list and it skips missing values automatically.

fastest_fouls = fouls.nlargest(5, 'exit_velocity')[['matchup', 'type_of_hit', 'exit_velocity', 'used_zone']]
fastest_fouls
matchup type_of_hit exit_velocity used_zone
100 Baltimore Orioles VS Minnesota Twins Line 110.6 4
341 Milwaukee Brewers vs New York Mets Fly 108.7 4
136 Baltimore Orioles VS Minnesota Twins Fly 108.5 6
140 Baltimore Orioles VS Minnesota Twins Fly 108.5 7
469 Texas Rangers vs Toronto Blue Jays Ground 107.6 5

Part 10: Real Average Exit Velocity by Hit Type#

Different types of contact produce different speeds, and knowing which is fastest helps judge risk. The code groups by type_of_hit, takes the mean exit_velocity for each group, rounds to one decimal and sorts from fastest to slowest. Line drives are the fastest on average at 82.2 mph, then fly balls at 76.7, ground balls at 74.4, pop ups at 74.3 and balls where the batter hit himself at 69.4. Remember that mean() ignores missing values, so each average only uses balls where speed was recorded.

velo_by_type = fouls.groupby('type_of_hit')['exit_velocity'].mean().round(1).sort_values(ascending=False)
velo_by_type
type_of_hit
Line                82.2
Fly                 76.7
Ground              74.4
Pop Up              74.3
Batter hits self    69.4
Name: exit_velocity, dtype: float64

Part 11: Real Velocity by Hit Type Chart#

A chart makes the gap between line drives and the other hit types easy to see. The code plots the averages from the previous step as horizontal bars with kind='barh', labels the axis in miles per hour, and saves the result to velocity_by_hit_type.png before closing the figure, so it does not appear in the notebook. When you open it, note that pandas draws a barh chart with the first value at the bottom, so the fastest type, line drives, appears at the bottom here. Sort ascending first if you want the longest bar on top.

fig, ax = plt.subplots(figsize=(8, 6))
velo_by_type.plot(kind='barh', ax=ax, color='firebrick')
ax.set_xlabel('Real Average Exit Velocity, MPH')
ax.set_title('Real Average Foul Ball Exit Velocity by Type of Hit')
plt.tight_layout()
plt.savefig('velocity_by_hit_type.png', dpi=100)
plt.close()

Part 12: Real Zone-by-Zone Average Velocity#

Linking speed to landing zone shows whether some areas receive harder-hit balls. The code groups by used_zone and takes the rounded mean exit_velocity for each zone. Zones 1 to 3 average between 70.7 and 72.8 mph, zones 4 and 5 are higher at 78.7 and 79.4 mph, and zones 6 and 7 stand out at 100.9 and 98.7 mph. Be careful with those last two: earlier counts showed only 6 and 5 balls in total in those zones, and fewer still may have a recorded speed, so their averages rest on very small samples.

velo_by_zone = fouls.groupby('used_zone')['exit_velocity'].mean().round(1)
velo_by_zone
used_zone
1     72.8
2     70.7
3     71.6
4     78.7
5     79.4
6    100.9
7     98.7
Name: exit_velocity, dtype: float64

Part 13: Real Predicted vs Camera-Confirmed Zone#

To test how good the prediction method is, you can only use balls where the camera confirmed the true zone. dropna(subset=['camera_zone']) keeps only rows where camera_zone has a value, and len() counts them. The output is 393 balls with camera confirmation. That is a little under half of the 905 tracked balls, matching the 512 missing values found earlier. Testing on this subset is fair, but it assumes the confirmed balls are not systematically different from the unconfirmed ones.

confirmed = fouls.dropna(subset=['camera_zone'])
len(confirmed)
393

Part 14: Real Prediction Agreement Rate#

This step measures how often the angle-based prediction matches the camera. Comparing predicted_zone with camera_zone using == gives True or False for each ball, and calling .mean() on that gives the share that are True, because True counts as 1 and False as 0. Multiplying by 100 and rounding gives a percentage. The output is 96.9, so the prediction matched the camera footage for almost 97% of confirmed balls. That is strong evidence that predicted_zone is a reasonable stand-in when no footage is available.

agreement_rate = round((confirmed['predicted_zone'] == confirmed['camera_zone']).mean() * 100, 1)
agreement_rate
np.float64(96.9)

Part 15: Real High-Velocity Dangerous Fouls#

Very fast fouls are the clearest safety concern, so counting them gives a headline risk figure. The code compares exit_velocity with 100 using >=, giving True for balls at or above 100 mph, and .sum() counts them. The output is 28 balls hit at 100 mph or faster. Missing speeds compare as False, so they are simply not counted. Because 326 speeds are missing, the true number of very fast fouls in these games could be higher.

high_velocity = (fouls['exit_velocity'] >= 100).sum()
high_velocity
np.int64(28)

Part 16: Real Share with Recorded Velocity#

Before trusting any speed-based finding, you should know what share of the data it covers. notna() returns True for every ball that has a speed, .mean() turns that into a share, and the code converts it to a percentage. The output is 64.0, so speed was recorded for 64% of tracked balls, which matches 579 out of 905. Quoting coverage like this alongside your averages is an honest habit that helps readers judge how far to trust them.

velocity_coverage = round(fouls['exit_velocity'].notna().mean() * 100, 1)
velocity_coverage
np.float64(64.0)

Part 17: Real Batter-Hits-Self Incidents#

Balls that hit the batter are a different kind of safety event, since the risk is to the player rather than the fans. The code compares type_of_hit with the exact text 'Batter hits self' and counts the matches with .sum(). The output is 17, the same figure shown in the hit type breakdown. The match must be exact, including capital letters and spaces, so copying the category name from an earlier output is safer than typing it from memory.

batter_hits_self = (fouls['type_of_hit'] == 'Batter hits self').sum()
batter_hits_self
np.int64(17)

Part 18: Real Fouls per Stadium Chart#

This chart shows the stadium counts from earlier in a form that is easier to compare. The code takes value_counts() on matchup, sorts ascending with sort_values() so the busiest game ends up at the top of a horizontal bar chart, and plots with kind='barh'. A wider figure gives room for the long matchup names. The chart is saved to fouls_by_stadium.png and closed, so it does not display in the notebook. When you open it, look for how close most games are, from 113 at the top to 66 at the bottom.

fig, ax = plt.subplots(figsize=(10, 6))
fouls['matchup'].value_counts().sort_values().plot(kind='barh', ax=ax, color='darkorange')
ax.set_xlabel('Real Number of Tracked Foul Balls')
ax.set_title('Real Foul Balls Tracked by Stadium Matchup, 2019')
plt.tight_layout()
plt.savefig('fouls_by_stadium.png', dpi=100)
plt.close()

Part 19: Real Ground Ball Share#

Shares are easier to compare across datasets than raw counts. Comparing type_of_hit with 'Ground' gives a True or False for each ball, and .mean() on that boolean gives the proportion that are True. Multiplying by 100 and rounding to one decimal turns it into a percentage. The output is 25.0, so exactly a quarter of tracked fouls were ground balls, consistent with 226 out of 905. This boolean-mean pattern is one of the most useful shortcuts in pandas.

ground_share = round((fouls['type_of_hit'] == 'Ground').mean() * 100, 1)
ground_share
np.float64(25.0)

Part 20: Real Fly Ball Share#

The same share calculation applied to fly balls shows how dominant they are. The code compares type_of_hit with 'Fly', takes the mean of the resulting booleans and converts it to a rounded percentage. The output is 57.6, so well over half of all tracked fouls were fly balls. Fly balls are the type most likely to reach the stands, which is why this share is relevant to a fan safety question.

fly_share = round((fouls['type_of_hit'] == 'Fly').mean() * 100, 1)
fly_share
np.float64(57.6)

Part 21: Real Zone 1 Share#

Zone 1 had the most balls of any zone, and expressing that as a share gives a clearer headline. The code compares used_zone with the number 1, not the text '1', because the column holds integers. The boolean mean, times 100 and rounded, gives 30.7, so almost a third of all tracked fouls landed in zone 1. Comparing a number column with a string is a common mistake that silently returns zero matches.

zone1_share = round((fouls['used_zone'] == 1).mean() * 100, 1)
zone1_share
np.float64(30.7)

Part 22: Real Duplicate Row Check#

Duplicate rows can inflate counts, so they are worth checking even late in an analysis. duplicated() with no arguments marks a row as True if every column exactly matches an earlier row, and .sum() counts them. The output is 212. In this dataset that does not automatically mean errors: two separate fouls in the same game, of the same type and zone, with missing speed and camera zone, would look identical. Inspect a few with fouls[fouls.duplicated(keep=False)] before deciding whether to remove anything.

fouls.duplicated().sum()
np.int64(212)

Part 23: Real High-Velocity Flag Column#

A flag column makes a definition reusable, so later steps do not have to repeat the threshold. The code creates is_dangerous, which is True whenever exit_velocity is 90 mph or more, and then counts the True values. The output is 74 balls flagged. Note the threshold here is 90, lower than the 100 mph used earlier, so this flag captures a wider group. Balls with no recorded speed are flagged False, so the flag really means 'known to be dangerous'.

fouls['is_dangerous'] = fouls['exit_velocity'] >= 90
fouls['is_dangerous'].sum()
np.int64(74)

Part 24: Saving the Real Enriched Dataset#

Saving the enriched data keeps the new is_dangerous column for future work. to_csv writes the DataFrame to foul_balls_enriched.csv, with index=False so no extra index column is added. The code then reads the file back and compares shapes, and the output True confirms the reloaded file has the same rows and columns as the original. This quick round trip catches problems such as a forgotten index=False adding a stray column.

fouls.to_csv('foul_balls_enriched.csv', index=False)
reloaded = pd.read_csv('foul_balls_enriched.csv')
reloaded.shape == fouls.shape
True

Part 25: Real Sanity Check, Row Count#

A final row count check confirms that no step accidentally dropped or duplicated rows. The code compares len(fouls) with 905, and the output True shows the DataFrame still holds every tracked ball. The subset used for camera agreement was stored in a separate variable, confirmed, so it did not change the main table. Keeping filtered subsets in new variables like this is a good way to protect the original data.

len(fouls) == 905
True

Part 26: Real Sanity Check, Hit Types Sum#

This check confirms that every ball has exactly one hit type. The code sums the counts from value_counts() on type_of_hit and compares the total with 905. The output np.True_ means the category counts add up to the full dataset, so no rows are missing a hit type and none are counted twice. If this ever failed, the first thing to look for would be missing values, because value_counts() skips them by default.

fouls['type_of_hit'].value_counts().sum() == 905
np.True_

Part 27: Real Sanity Check, Core Columns Complete#

Some columns must be complete for the main analysis to hold, and this step tests them together. The code selects matchup, game_date, type_of_hit and used_zone, counts missing values per column with isna().sum(), then adds those counts with a second .sum(). Comparing the total with zero gives np.True_, so all four core columns are fully populated. The double .sum().sum() is a handy pattern for counting every missing cell across several columns at once.

fouls[['matchup', 'game_date', 'type_of_hit', 'used_zone']].isna().sum().sum() == 0
np.True_

Part 28: Real Sanity Check, Ten Stadiums#

The dataset is described as covering ten stadiums, and this step confirms it. nunique() counts distinct values in matchup, and comparing the result with 10 returns True. That matches the ten matchups listed in the stadium breakdown. Strictly, each matchup stands for one game at one stadium, so if the data were extended to more games per stadium you would want a separate stadium column for this check.

fouls['matchup'].nunique() == 10
True

Part 29: Real Top Finding Print#

A finding is most useful when it is written as a plain sentence. The code takes the first row of the fastest_fouls table with .iloc[0] and reads its exit_velocity and used_zone. The printed output says the fastest tracked foul left the bat at 110.6 mph and landed in zone 4. Because nlargest already sorted the rows, the first row is guaranteed to be the fastest, and building the sentence from variables means it stays correct if the data changes.

fastest_velo = fastest_fouls.iloc[0]['exit_velocity']
fastest_zone = fastest_fouls.iloc[0]['used_zone']
print(f'The real fastest tracked foul ball left the bat at {fastest_velo} miles per hour and landed in real zone {fastest_zone}.')
The real fastest tracked foul ball left the bat at 110.6 miles per hour and landed in real zone 4.

Part 30: Real Recap Print#

The recap pulls the main safety findings into one sentence a non-technical reader can use. The f-string combines the total number of balls, the count hit at 100 mph or more and the prediction agreement rate. The printed output says that across 905 tracked foul balls at 10 stadiums, 28 were hit at least 100 mph, and prediction from angle alone matched camera footage 96.9% of the time. When you share it, it is worth adding that speed was recorded for only 64% of balls.

print(f'Across {len(fouls)} real tracked foul balls at 10 real stadiums, {high_velocity} were hit at least 100 miles per hour, and prediction from angle alone matched real camera footage {agreement_rate} percent of the time.')
Across 905 real tracked foul balls at 10 real stadiums, 28 were hit at least 100 miles per hour, and prediction from angle alone matched real camera footage 96.9 percent of the time.

Wrap-Up: What You Learned#

  • This real dataset covers nine hundred five real foul balls tracked at ten real MLB stadiums in 2019, with real missing exit velocity and camera zone values honestly explained by real limits of the footage.
  • Real fly balls were the real most common type of foul, and real exit velocity varied meaningfully by real type of hit and real landing zone.
  • Predicting a real landing zone from angle alone matched real camera-confirmed footage a real specific, measurable percentage of the time, an honest test of this real method's accuracy.
  • This real domain has now covered seven genuinely different competitive contexts, basketball, tennis, baseball twice from different angles, football, soccer, and chess, using seven real independently sourced datasets.
  • Every real number in this lesson traces back to genuinely real, complete FiveThirtyEight footage-tracking data, the same honest-sourcing standard carried through every domain so far.
  • Next video: a real NFL ticket pricing dataset, continuing this domain with a return to football from an economics angle.

Practice on your own

  1. Group by matchup and calculate the share of balls flagged is_dangerous in each game, then sort to see which game produced the highest share of fast fouls.
  2. Build a cross-table of type_of_hit against used_zone with pd.crosstab and find which hit type sends the most balls into zone 1.
  3. For the 393 camera-confirmed balls, list the rows where predicted_zone and camera_zone disagree and check whether they share a hit type or a zone.

The next lesson in the series returns to football with a real NFL ticket pricing dataset, looking at the sport from an economics angle. 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.