Appendix A — Python and pandas for F1
This appendix is a self-contained primer on the Python you need to read and change every script in the book. It is written for two readers. The first has never used pandas and wants to follow the chapters' code without guessing. The second knows pandas from another field and wants the handful of habits that F1 timing data demands: grouping by stint rather than by driver, filtering laps with one agreed rule, aligning two laps on distance, and putting an interval on every number.
Everything here runs on the book's own data snapshot. The examples live in one script,
appendices/code/appendix_a_examples.py, which prints a header (== A.2.3 and so on) for each section
below. The output blocks in this appendix are pasted from a real run of that script. Run it yourself from
the book root:
python appendices/code/appendix_a_examples.py
It finishes in a few seconds and makes no network calls.
Two things this appendix does not do. It doesn't repeat the data-pipeline story: how the OpenF1 archive was downloaded, how the build decides which stint a lap belongs to, how the two sources are joined and checked against each other. That is Chapter 2. It also doesn't list every column and function. That is Appendix B. Think of this appendix as the grammar, Chapter 2 as the first long reading, and Appendix B as the dictionary.
We use one race throughout: the 2025 Mexico City Grand Prix (round 20, 71 laps), the race behind the book's degradation anchor in Chapter 22. For telemetry we switch to 2025 Japanese Grand Prix qualifying, where Verstappen took pole from Norris by 0.012 s, the speed-trace anchor of Chapter 19.
A.1 Setting up
What you need
You need Python 3.11 or later; the book was built and tested on 3.13. You also need the scientific stack
listed in requirements.txt at the book root: pandas, numpy, scipy, statsmodels, scikit-learn,
matplotlib, seaborn, plotly (optional, for HTML charts), pyarrow (to read the parquet tables), requests
(used only by the download scripts) and pytest (for the toolkit's tests).
python -m venv .venv # optional but recommended: a private environment for the book
.venv\Scripts\activate # Windows; on macOS/Linux: source .venv/bin/activate
pip install -r requirements.txt
python -m pytest toolkit/tests -q # the toolkit's tests run against the real processed data
A virtual environment is a folder that holds its own copy of Python's packages. It keeps the book's versions from colliding with anything else on your machine, and you can delete it without harm.
FastF1 appears in requirements.txt only as a commented-out optional line, because since 2026 its
official timing source needs an F1 TV subscription. Nothing in this appendix, or anywhere else in the
book, depends on it. Appendix J explains how to use it if you
have a subscription.
The script header
Every script in the book begins with the same few lines. Here is the version for a script in
appendices/code/ (two folders below the book root; chapter scripts sit three folders down, so they use
parents[3]):
import sys
from pathlib import Path
sys.stdout.reconfigure(encoding="utf-8") # accented names (Pérez, Hülkenberg) print on Windows
BOOK = Path(__file__).resolve().parents[2] # appendices/code/ -> the book root
sys.path.insert(0, str(BOOK)) # so "import toolkit" works
sys.path.insert(0, str(BOOK / "project")) # so "import boxbox" works
import matplotlib
matplotlib.use("Agg") # draw charts to files, never open a window
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from toolkit import f1data, metrics, plots, telemetry, history
Line by line:
sys.stdout.reconfigure(encoding="utf-8")stops Windows consoles from crashing on "Sergio Pérez". Jolpica stores names with their accents, and you want them printed correctly.Path(__file__).resolve().parents[2]walks up from the script's own location.parents[0]is the script's folder,parents[1]its parent, and so on. Because the path is computed from the file and not from your current directory, the script works wherever you run it from.sys.path.insert(0, …)tells Python where to look for imports. The toolkit lives in the book root and the Box Box package inproject/.matplotlib.use("Agg")picks a back end that writes PNG files. It must come beforeimport matplotlib.pyplot.- The last line imports the five toolkit modules.
f1dataloads the OpenF1 tables (2023 onward),historyloads the Jolpica tables (1950 onward),metricsholds the book's canonical definitions,telemetryloads and slices car data, andplotsgives the house chart style.
A first check
The first section of the example script prints the versions and three counts, which tells you the install works and the data is where the toolkit expects it:
print("sessions (testing excluded):", len(f1data.sessions()))
print("sessions (testing included):", len(f1data.sessions(include_testing=True)))
print("Jolpica results rows:", len(history.results()))
== A.1 Environment check
python 3.13.12
pandas 2.3.3
numpy 2.3.5
matplotlib 3.10.9
scipy 1.17.0
statsmodels 0.14.6
sklearn 1.8.0
pyarrow 24.0.0
sessions (testing excluded): 455
sessions (testing included): 470
Jolpica results rows: 26335
If you get DataMissingError: … not found. Build it with: python scripts/build_openf1.py, the processed
tables are missing. Appendix J §J.7 explains how to rebuild
them. If your counts differ from these, your snapshot is newer or older than the book's. That is fine, but
expect the printed numbers in the chapters to differ slightly from yours.
⚠️ Common pitfall: running from the wrong Python. If import pandas fails although you installed it,
you probably have two Pythons and installed into the other one. Run python -m pip install -r
requirements.txt with the same python you use to run scripts, or activate the virtual environment
first.
A.2 pandas essentials
pandas gives Python a table type, the DataFrame: rows and named columns, where each column has one data type. Nearly every object the toolkit returns is a DataFrame, so the whole book is, in a sense, an exercise in about a dozen DataFrame operations. This section covers them in the order you'll need them.
A.2.1 A DataFrame is a table
race = f1data.session(2025, "Mexico City", "R") # one row describing the session
lp = f1data.laps(race) # every lap of every driver in it
print("shape:", lp.shape)
print(lp[["acronym", "lap_number", "lap_duration", "compound", "tyre_age", "track_status", "is_clean"]]
.head(4).to_string(index=False))
print(lp.dtypes[["lap_number", "lap_duration", "tyre_age", "date_start", "is_clean", "segments_sector_1"]])
== A.2.1 A DataFrame is a table: shape, columns, dtypes
session_key 9877 | Mexico City Grand Prix R | leader laps 71
shape: (1266, 49)
acronym lap_number lap_duration compound tyre_age track_status is_clean
VER 1 88.233 MEDIUM 0 GREEN False
VER 2 83.412 MEDIUM 1 GREEN True
VER 3 82.702 MEDIUM 2 YELLOW False
VER 4 82.787 MEDIUM 3 YELLOW False
lap_number int64
lap_duration float64
tyre_age Int64
date_start datetime64[ns, UTC]
is_clean bool
segments_sector_1 object
dtype: object
f1data.session() returns a single row (a pandas Series) holding the session's keys and facts: its
session_key (9877), its round, its name and the number of laps the leader completed. Pass that row to
any loader and you get that session's data. You could equally pass the key itself, f1data.laps(9877).
The laps table for this race has 1,266 rows (one per driver per lap) and 49 columns. Five dtypes are worth recognising now, because each behaves differently:
int64andfloat64are ordinary numbers. Lap times are floats in seconds.Int64, with a capital I, is pandas' nullable integer: an integer column that can also hold missing values (<NA>).tyre_ageis one, because a few laps have no stint information.datetime64[ns, UTC]is a timestamp with a time zone. Every OpenF1 time in the book is in UTC.boolis True/False. Theis_*flags are booleans, which makes them perfect filters.objecthere holds Python lists: the mini-sector codes for each sector.
Notice that row 1 has track_status GREEN but is_clean False. Lap 1 is never clean, whatever the
flags say. Rows 3 and 4 are not clean because a yellow flag overlapped them. Appendix B lists the exact
definition of every column.
A.2.2 Selecting rows and columns
Three ways to choose rows cover almost everything.
nor = lp[lp.acronym == "NOR"] # 1. a boolean mask
print(nor.loc[nor.lap_number.between(33, 37), # 2. .loc[rows, columns]
["lap_number", "lap_duration", "compound", "tyre_age", "is_pit_in_lap", "is_pit_out_lap"]])
q = lp.query("compound == 'SOFT' and is_clean and lap_duration < 81") # 3. a query string
print(len(lp[lp.acronym.isin(["NOR", "LEC", "VER"])])) # membership in a list
== A.2.2 Selecting rows and columns
NOR laps: 71
lap_number lap_duration compound tyre_age is_pit_in_lap is_pit_out_lap
33 83.304 SOFT 32 False False
34 86.035 SOFT 33 True False
35 101.386 MEDIUM 0 False True
36 82.205 MEDIUM 1 False False
37 81.999 MEDIUM 2 False False
clean SOFT laps under 1:21.000: 48 by ['ALB', 'ANT', 'BEA', 'HAM', 'PIA', 'RUS', 'SAI', 'STR']
top-3 finishers' laps: 213
The expression lp.acronym == "NOR" produces a column of True/False values, one per row. Putting it in
square brackets keeps the rows where it is True. You can combine masks with & (and), | (or) and ~
(not), but each condition needs its own parentheses: lp[(lp.acronym == "NOR") & lp.is_clean].
.loc[rows, columns] selects both at once. between(33, 37) is inclusive at both ends.
The five laps around Norris's stop show how the data encodes a pit stop. Lap 34 is the in-lap
(is_pit_in_lap), where he entered the pit lane at the end of the lap. Lap 35 is the out-lap, 101.386 s
long because it includes the time in the pit lane, and the first lap on a new set of MEDIUMs, so its
tyre_age is 0. Tyre age counts the laps already completed on the set when the lap began. The SOFTs he
took off had done 33 laps.
query() is the same filter written as a string, which some people find easier to read. Inside the
string, column names are bare and text values need quotes.
⚠️ Common pitfall: and versus &. Writing lp[(lp.acronym == "NOR") and lp.is_clean] raises
"The truth value of a Series is ambiguous". Python's and wants one True or False; a mask holds
thousands. Use & outside query() and and inside it.
A.2.3 Counting and summarising
print(lp.track_status.value_counts())
print("share of laps clean: %.3f" % lp.is_clean.mean())
print(lp.loc[lp.is_clean, "lap_duration"].describe().round(3))
== A.2.3 Counting and summarising
track_status
GREEN 1156
YELLOW 74
VSC|YELLOW 25
VSC 7
UNKNOWN 4
share of laps clean: 0.855
lap_duration describe (clean laps, s):
count 1082.000
mean 82.782
std 1.165
min 80.052
25% 81.922
50% 82.643
75% 83.665
max 88.796
value_counts() is the quickest way to see what a column contains. Here it shows that track_status can
combine statuses (VSC|YELLOW means both were present during the lap) and that four laps had no
timestamps to compare with the flag windows (UNKNOWN).
The mean of a boolean column is the share of True values: 85.5 % of this race's laps are clean. That is a little above the 83.3 % share for all race laps in the snapshot, which is what you'd expect from a race with only one short virtual safety car (VSC).
describe() gives the count, mean, spread and quartiles. Look at the minimum (80.052 s) and the maximum
(88.796 s) of the clean laps. The spread of 8.7 s is not noise in the data. It is fuel, tyres, traffic and
the difference between cars, which is exactly what the rest of the book takes apart.
A.2.4 groupby: split, apply, combine
Most F1 questions are "for each driver…", "for each stint…", "for each circuit…". In pandas that is
groupby: split the table into groups, compute something in each, and combine the results into a new
table.
per_driver = (lp[lp.is_clean]
.groupby(["acronym", "team_ref"], as_index=False)
.agg(n=("lap_duration", "size"),
median_s=("lap_duration", "median"),
best_s=("lap_duration", "min"))
.sort_values("median_s"))
per_driver["best"] = per_driver.best_s.map(fmt_lap) # 80.764 -> '1:20.764'
== A.2.4 groupby: one row per driver
acronym team_ref n median_s best_s best
NOR mclaren 62 82.030 80.764 1:20.764
LEC ferrari 61 82.235 81.588 1:21.588
HAM ferrari 59 82.288 80.601 1:20.601
PIA mclaren 60 82.340 80.422 1:20.422
RUS mercedes 59 82.381 80.052 1:20.052
BEA haas 60 82.427 80.705 1:20.705
The agg call uses named aggregation: each keyword becomes an output column, defined as a pair
(input column, function). "size" counts rows, and "median" and "min" do what they say. You can pass
your own function too, for example ("lap_duration", lambda s: s.quantile(0.1)).
Read the result as a strategist would. Norris had the lowest median clean lap. Russell set the single fastest lap (1:20.052) but sits fifth on the median. A fastest lap is one point from a distribution, often set on fresh tyres near the end with nothing to lose. The median describes the race.
fmt_lap is a five-line helper in the script that turns seconds into the book's 1:20.764 format:
def fmt_lap(sec):
m, s = divmod(float(sec), 60) # 80.764 -> (1.0, 20.764)
return f"{int(m)}:{s:06.3f}" # zero-pad the seconds to 6 characters: 20.764, 05.120
Series.map(f) applies a function to every value of a column. For arithmetic, prefer vectorised
operations (§A.3); map is for formatting and lookups.
Two more groupby tools appear constantly in the chapters:
groupby(...).transform("median")returns a column the same length as the original, with each row holding its group's median. That is how you compare each lap with its own driver's median without a merge (§A.5.2 uses it).groupby(...).apply(f)runs any function on each group's sub-table. It is flexible but slow; reach for it only whenaggandtransformcan't express what you need.
A.2.5 merge: joining two tables
The two sources the book uses describe the same races from different angles. OpenF1 has laps, tyres and
flags; Jolpica has the official classification and seventy-seven seasons of history. You join them with
merge, on a key both share. The toolkit maps every OpenF1 driver to a Jolpica driver_ref, so that is
the natural key.
pace = metrics.race_pace(race) # canonical race pace: median fuel-corrected clean lap
res = history.results(2025, int(race["round"]))[["driver_ref", "grid", "position", "status_text", "finished"]]
m = pace.merge(res, on="driver_ref", how="left", validate="one_to_one", indicator=True)
print(m._merge.value_counts())
== A.2.5 merge: OpenF1 race pace + Jolpica classification
_merge
both 19
left_only 0
right_only 0
acronym n_laps pace_s gap_s grid position status_text
NOR 62 80.527 0.000 1 1 Finished
HAM 59 80.719 0.193 3 8 Finished
PIA 60 80.761 0.235 7 5 Finished
VER 61 80.836 0.309 5 3 Finished
BEA 60 80.839 0.313 9 4 Finished
ANT 60 80.843 0.316 6 6 Finished
LEC 61 80.982 0.455 2 2 Finished
RUS 59 81.008 0.481 4 7 Finished
Spearman rank corr(pace, finish), finishers only: 0.829
Three arguments make a merge safe:
how="left"keeps every row of the left table, whether or not it finds a partner. ("inner"keeps only matches,"outer"keeps everything.)validate="one_to_one"makes pandas raise an error if either side has duplicate keys. A duplicated key silently multiplies rows, which is the commonest way to get wrong totals.indicator=Trueadds a_mergecolumn saying where each row came from. Here all 19 drivers with clean laps found their Jolpica result. One car (Lawson, who retired after completing five laps) had no clean laps, so he is not inpaceat all.
pace_s here (80.527 s for Norris) is lower than the raw median in §A.2.4 (82.030 s). That is the fuel
correction: race_pace subtracts the time cost of the fuel still on board, using the toolkit's stated
assumptions (100 kg at the start, 0.03 s per kg per lap). Chapter 20
explains why every pace or degradation number must say which correction it used.
The table also shows why pace and result are related but not the same. Hamilton had the second-best race pace and finished eighth; Leclerc, seventh on pace, finished second. The rank correlation among finishers is 0.83: strong, not perfect. Track position, the timing of stops and incidents fill the gap, and the data alone doesn't tell you which applied to which driver. You would look at race control, the stints and the gaps before saying anything.
⚠️ Common pitfall: _x and _y columns. If both tables have a column with the same name that is not
a key (say team_ref), pandas keeps both and renames them team_ref_x and team_ref_y. Select only the
columns you need from the right-hand table before merging, as the code above does. history.laps()
already carries team_ref and abbreviation, so merging results onto it is a classic way to trip on this.
A.2.6 Time: timestamps, zones and durations
F1 data has three kinds of time, and mixing them up is the source of many subtle bugs.
- Instants:
date_start,date_end, and thedateof each race-control message, weather reading and telemetry sample. These are timestamps in UTC. - Durations:
lap_duration, the sector times andpit_lane_s, stored as floats in seconds. - Elapsed time: the time since some reference instant, computed by subtracting two timestamps.
first = lp[lp.lap_number == 1].date_start.min() # the first car starts lap 1
off = pd.to_timedelta(race.gmt_offset) # '-06:00:00' -> a Timedelta
print("local start", (first + off).tz_localize(None))
lp = lp.assign(elapsed_min=(lp.date_end - first).dt.total_seconds() / 60)
print(pd.to_timedelta(80.764, unit="s")) # seconds -> Timedelta
wx = f1data.weather(race)
print(wx.date.sort_values().diff().median()) # typical spacing of weather records
== A.2.6 Time: timestamps, time zones, durations
lights out (UTC): 2025-10-26 20:03:15.881000+00:00
gmt_offset: -06:00:00 -> local start 2025-10-26 14:03:15.881000
NOR crossed the line for the last time 97.98 min after the start
lap time as Timedelta: 0 days 00:01:20.764000 | formatted: 1:20.764
weather records: 162 | median interval: 0 days 00:01:00.001000
Subtracting two timestamps gives a Timedelta; .dt.total_seconds() turns a column of them into floats,
which is almost always what you want for arithmetic. The session's gmt_offset string converts to local
time when you want to say "the race started at 14:03 local". Keep calculations in UTC, and convert only
for display.
The weather stream updates about once a minute (the median spacing printed above). That is why the
toolkit attaches the nearest weather record to each lap rather than an exact one. Joining two time series
by "the nearest earlier record" is pd.merge_asof, which the toolkit uses for positions, gaps and
weather:
pd.merge_asof(laps.sort_values("date_end"), weather.sort_values("date"),
left_on="date_start", right_on="date", by="session_key",
direction="nearest", tolerance=pd.Timedelta("10min"))
Both tables must be sorted on the time column. by= restricts matches to the same session, and
tolerance= refuses matches that are too far apart (they become NaN instead of a stale value).
⚠️ Common pitfall: comparing a time-zone-aware timestamp with a naive one. pandas refuses to compare
2025-10-26 20:03+00:00 with 2025-10-26 20:03 and raises a TypeError. Create comparison timestamps
with a zone: pd.Timestamp("2025-10-26 20:00", tz="UTC").
A.2.7 Long and wide
The laps table is long: one row per driver per lap. Some questions are easier on a wide table, with one row per lap and one column per driver, for example "on lap 42, who was quicker?".
wide = lp.pivot_table(index="lap_number", columns="acronym", values="lap_duration")
print(wide.loc[40:43, ["NOR", "LEC", "VER", "BEA"]].round(3))
== A.2.7 Long to wide: pivot_table
acronym NOR LEC VER BEA
lap_number
40 81.523 82.235 81.425 82.203
41 81.694 82.115 81.447 82.499
42 81.487 81.813 81.349 82.332
43 81.531 81.857 81.348 82.393
On these four laps Verstappen, on a used set of SOFTs fitted at his stop after lap 37, was between 0.098 s
and 0.247 s a lap quicker than Norris on his MEDIUMs. A wide table makes that kind of comparison
quick to read, and wide["VER"] - wide["NOR"] gives the lap-by-lap difference in one line. To go back
from wide to long, use wide.reset_index().melt(id_vars="lap_number", var_name="acronym",
value_name="lap_duration"). Keep the data long for storage and grouping, and go wide only for display or
for one-off comparisons.
🔄 Check your understanding 1. You want each driver's number of pit stops in a race from the laps table. Which column do you filter, and which pandas operation counts per driver? 2. Why does
lp[lp.acronym == "NOR" & lp.is_clean]fail, and how do you fix it? 3. A merge of race pace onto results gives 38 rows for a 19-driver race. What went wrong, and which argument would have caught it?
Answer
- Filter
is_pit_in_lap, thengroupby("acronym").size()(or.is_pit_in_lap.sum()per driver without filtering). Check red-flag tyre changes separately: a change during a red flag is not a stop.&binds more tightly than==, so Python evaluates"NOR" & lp.is_cleanfirst. Put each condition in parentheses:lp[(lp.acronym == "NOR") & lp.is_clean].- The right-hand table had each driver twice (for example, race and sprint results stacked together), so every left row matched two right rows.
validate="one_to_one"(or"many_to_one") raises an error instead of silently doubling the rows.
A.3 numpy: arrays and vectorised arithmetic
Underneath every pandas column is a numpy array: a block of numbers of one type, with arithmetic that runs on the whole block at once. You'll use numpy directly for formulas, for fitting lines, for interpolation and for random numbers.
Vectorised formulas
The toolkit's fuel correction is a one-line formula. Writing it by hand is a good way to see what "vectorised" means: no loop, one expression over all 71 laps.
L = nor.lap_number.to_numpy(float) # lap numbers as a float array
N = int(race.leader_laps) # 71
fuel = 100 * (1 - (L - 0.5) / N) # ASSUMPTION: 100 kg at the start, linear burn, mid-lap
fc_manual = nor.lap_duration.to_numpy(float) - 0.03 * fuel # ASSUMPTION: 0.03 s per kg per lap
fc_toolkit = metrics.fuel_corrected(nor).lap_time_fc.to_numpy(float)
print(np.allclose(fc_manual, fc_toolkit, equal_nan=True))
$$t_{\text{fc}} = t - k\,m_0\left(1 - \frac{L - 0.5}{N}\right)$$
In words: take the lap time $t$ and subtract what the fuel still on board costs, where $m_0$ is the starting fuel mass, $k$ the cost per kilogram and $N$ the race distance in laps. With the default assumptions, a lap-1 time loses 0.03 × 100 × (1 − 0.5/71) = 2.979 s, and the last lap loses 0.021 s. The result is the lap time the car would have done with an empty tank, which puts every lap of the race on a common footing.
np.allclose(..., equal_nan=True) compares two float arrays with a small tolerance, treating NaN = NaN as
equal. Never test floats with ==: rounding differences in the last digit are normal.
Fitting a line
st = metrics.fuel_corrected(nor)
st = st[(st.stint == 1) & st.is_clean & (st.stint_lap > 1)] # first stint, clean, after the warm-up lap
slope, intercept = np.polyfit(st.tyre_age.to_numpy(float), st.lap_time_fc.to_numpy(float), 1)
d = metrics.degradation(st) # the canonical version, with a 95% CI
== A.3 numpy: arrays, vectorised arithmetic, fitting, interpolation, random numbers
manual == toolkit fuel correction: True
np.polyfit slope, NOR stint 1: 0.0637 s/lap (n = 28)
metrics.degradation slope: 0.0637 s/lap 95% CI [0.0499, 0.0775]
np.interp: fuel at lap 35.5 = 50.7 kg (assumed model)
seeded draws: [ 0.0914 -0.312 0.2251]
np.polyfit(x, y, 1) fits a straight line by least squares and returns the slope and intercept. Here it
says that, fuel-corrected with the default assumptions, Norris's first-stint SOFTs lost 0.0637 s per lap
of tyre age over 28 usable laps. metrics.degradation fits the same line (it drops stint lap 1 and
non-clean laps itself) and adds the 95 % confidence interval, 0.050–0.078 s/lap. Use the toolkit version
in anything you publish: it is the book's definition, and it carries its uncertainty with it.
Chapter 22 builds the
full degradation model, and Chapter 4 explains why the
raw, uncorrected slope would understate the wear.
The .to_numpy(float) calls matter. tyre_age is a nullable Int64 column, and some numerical
libraries don't accept pandas' <NA>. Converting to a plain float array turns missing values into NaN,
which numpy understands.
Interpolation
np.interp(x_new, x, y) estimates y at new x positions by drawing straight lines between the known
points. The x values must be increasing. The line printed above, "fuel at lap 35.5 = 50.7 kg", is the
assumed fuel model read halfway through lap 35. Interpolation is the workhorse of telemetry alignment
(§A.5.3), where it puts two laps' samples onto the same distance grid.
Random numbers with a seed
rng = np.random.default_rng(42) # a generator with a fixed seed
rng.normal(0, 0.3, 3) # three draws from N(0, 0.3^2): the same three every run
Monte Carlo simulation, bootstrapping and train/test splits all use random numbers. The book seeds every
one of them (usually with 42), so every printed number can be reproduced exactly. Make a generator once
with default_rng(seed) and draw from it. Avoid the older np.random.seed() global state, which any
other piece of code can disturb.
A.4 Charts with matplotlib and toolkit.plots
matplotlib draws a figure (the whole image) containing one or more axes (the plotting panels).
You add lines and points to an axes, label it and save the figure. The toolkit's plots module sets the
book's house style and handles saving and source notes, so your scripts only draw.
plots.use_style() # fonts, grid, colours: the house style
fig, ax = plt.subplots(figsize=(10, 5.2))
for drv, ls, mk in (("NOR", "-", "o"), ("LEC", "--", "s")): # line style and marker identify the driver
g = metrics.fuel_corrected(lp[(lp.acronym == drv) & lp.is_clean])
for (stint, comp), gs in g.groupby(["stint", "compound"]):
ax.plot(gs.lap_number, gs.lap_time_fc, ls=ls, marker=mk, ms=3.5, lw=1.2,
color=plots.compound_color(comp), mec="#333333", mew=0.4,
label=f"{drv} stint {stint} ({comp})")
ax.set_xlabel("Lap")
ax.set_ylabel("Fuel-corrected lap time (s)")
ax.set_title("2025 Mexico City GP: NOR lapped quicker than LEC through most of both stints")
ax.legend(ncol=2, fontsize=8, loc="upper right")
plots.add_source(fig, f1data.source_note(race) + ". Clean laps only; line style = driver, colour = compound.")
plots.savefig(fig, APPENDIX_DIR, "appa-fig-01-mexico-2025-clean-laps") # -> images/appa-fig-01-....png

📊 Figure (described): Fuel-corrected clean laps for Norris (solid line, circles) and Leclerc (dashed line, squares), red on SOFTs and yellow on MEDIUMs. Both first stints rise steadily as the SOFTs wear, Leclerc's more steeply; both drivers stopped in the early thirties, and after the stop the MEDIUM laps start lower and climb again. Norris's line sits below Leclerc's on most laps of both stints, which is the 0.455 s race-pace gap of §A.2.5 seen lap by lap.
The house rules for every chart in the book apply here too. Each axis is labelled with units. The title states the finding, not just the subject. The source note under the chart names the data. Colour is never the only cue: the two drivers share the compound colours, so line style and marker shape distinguish them, which also keeps the chart readable for colour-blind readers. Compound colours are fixed across the book (SOFT red, MEDIUM yellow, HARD white with a dark edge, INTERMEDIATE green, WET blue).
The toolkit also has ready-made charts for the most common views: speed_trace, track_map,
position_chart, gap_chart, stint_chart and deg_plot. One line draws a race's tyre strategies:
fig = plots.stint_chart(race)
plots.savefig(fig, APPENDIX_DIR, "appa-fig-02-mexico-2025-stints")

📊 Figure (described): One bar per driver in finishing order, split into stints coloured by compound. The top three each made one stop: Norris and Leclerc went SOFT to MEDIUM, Verstappen MEDIUM to SOFT. Most of the points finishers behind them made two stops (SOFT, MEDIUM, SOFT). Albon and Colapinto ran long first stints on HARDs. Short bars at the bottom are retirements.
plots.savefig writes a 150 dpi PNG into the images/ folder next to the chapter or appendix and returns
the relative path to paste into the markdown. It closes the figure too, which matters in scripts that draw
dozens of charts. Chapter 25 is the
full treatment of F1 charts, including contrast checks and colour-blind simulation.
⚠️ Common pitfall: emoji in chart text. The house font cannot draw emoji, so a 🧪 in a title shows up as an empty box. Write "Illustrative model:" in words inside figures.
⚠️ Common pitfall: two y-axes. It is tempting to plot lap time and track temperature on one panel
with a second y-axis. The book never does this: the reader can't tell which line belongs to which scale,
and the apparent correlation depends on how you set the two ranges. Use two panels stacked with
plt.subplots(2, 1, sharex=True).
A.5 F1 data idioms
The operations above are general pandas. This section is about the habits that F1 timing data needs.
A.5.1 One row per stint
A driver's race is a sequence of stints, and almost every tyre question is asked per stint. Group by driver and stint:
stints = (lp.groupby(["acronym", "stint"], as_index=False)
.agg(compound=("compound", "first"), first_lap=("lap_number", "min"),
last_lap=("lap_number", "max"), start_age=("tyre_age", "min"),
clean=("is_clean", "sum")))
stints["laps"] = stints.last_lap - stints.first_lap + 1
deg = metrics.degradation_table(race) # degradation() for every stint with >= 6 usable laps
deg.groupby("compound").slope_s_per_lap.agg(["count", "median"])
== A.5.1 Idiom: one row per stint
acronym stint compound first_lap last_lap start_age clean laps
LEC 1 SOFT 1 31 0 25 31
LEC 2 MEDIUM 32 71 0 36 40
NOR 1 SOFT 1 34 0 28 34
NOR 2 MEDIUM 35 71 0 34 37
VER 1 MEDIUM 1 37 0 31 37
VER 2 SOFT 38 71 3 30 34
degradation_table (fuel-corrected, default assumptions), median slope by compound:
count median
compound
HARD 2 0.0257
MEDIUM 16 0.0491
SOFT 27 0.0565
Summing a boolean column counts its True values, so clean is the number of usable laps in each stint.
start_age shows that Verstappen's second set of SOFTs had already done 3 laps, in qualifying, before he
fitted them. That is why tyre age is not the same as stint lap.
metrics.degradation_table runs the canonical degradation fit on every stint with at least six usable
laps. Across the field, with the toolkit's default fuel correction, the median SOFT stint lost 0.0565 s
per lap of tyre age and the median MEDIUM stint 0.0491 s. With only two HARD stints, the HARD median means
little. Always print count next to a median.
The stints table you'd use for strategy work is f1data.stints(race), which comes straight from OpenF1
and records the stint boundaries the build corrected. Grouping the laps as above gives you the same
boundaries, plus anything you want to compute per stint.
⚠️ Common pitfall: phantom stints. OpenF1 occasionally inserts an empty or zero-length stint when a
car drives through the pit lane without changing tyres, and a red-flag tyre change also starts a new
stint. Counting stints minus one is therefore not always the number of stops. Appendix B's caveats list
the known cases; count stops from is_pit_in_lap with a pit-lane time under 60 s, or use the stop
definitions in Chapter 12.
A.5.2 Filtering laps the canonical way
Every chapter that measures pace uses the same clean-lap rule, and the laps table carries it precomputed
as is_clean. Rebuilding it by hand is the best way to understand it:
cand = ((lp.lap_number > 1) # 1. not the standing-start lap
& ~lp.is_pit_in_lap & ~lp.is_pit_out_lap # 2. not an in-lap or out-lap
& (lp.track_status == "GREEN") # 3. no SC, VSC, red or yellow during the lap
& lp.lap_duration.notna()) # 4. a timed lap
med = lp.lap_duration.where(cand).groupby([lp.driver_number, lp.stint]).transform("median")
mine = cand & (lp.lap_duration <= 1.07 * med) # 5. within 107 % of the driver's stint median
print((mine == lp.is_clean).all())
== A.5.2 Idiom: filtering laps the canonical way
rule-by-rule: {'all': 1266, 'not_lap1': 1246, 'candidates': 1083, 'clean': 1082}
matches is_clean: True
neutralisations: [{'status': 'VSC', 'start_lap': 70.0, 'duration_s': 100.0}]
Two pandas tricks carry this. where(cand) blanks out (sets to NaN) the laps that fail rules 1–4, so the
median in rule 5 is computed only over candidate laps. transform("median") then hands each lap its own
driver-stint median, so the comparison is one vectorised line. Of this race's 1,266 laps, 1,083 pass rules
1–4 and 1,082 survive the 107 % test; the hand-built mask matches is_clean on every lap.
The 107 % reference is the driver's own stint median, not the session's fastest lap. That keeps a slow car's representative laps and still removes a quick car's traffic or mistake laps. Chapter 2 §2.6 shows how much that choice matters.
The one neutralisation, a 100 s VSC late in the race, comes from f1data.track_periods, the table of SC,
VSC, red and yellow windows built from race-control messages. If you need to know why a lap is not clean,
look there and in f1data.race_control(race).
📐 Definition: clean lap. A lap is clean when it is not lap 1, not a pit in-lap or out-lap, GREEN for
its whole duration, timed, and no slower than 107 % of the same driver's median green lap in the same
stint. In code: f1data.laps(session, clean=True) or the is_clean column.
A.5.3 Aligning two laps on distance
Comparing two qualifying laps means putting them on a common horizontal axis. Time is the wrong axis: by the end of the lap the two cars are at different places at the same moment. Distance is the right one, but OpenF1 doesn't measure distance. The toolkit integrates it from the speed channel, and the result drifts.
qs = f1data.session(2025, "Japanese", "Q")
ver = telemetry.fastest_lap_telemetry(qs, "VER") # one lap, with time_s and integrated distance_m
nor_t = telemetry.fastest_lap_telemetry(qs, "NOR")
uni = telemetry.delta_time(ver, nor_t) # default: rescale both laps to the same length
The toolkit's default, delta_time(ref, cmp), stretches the comparison lap uniformly so that both laps
have the same total length, then interpolates each lap's elapsed time onto a 5 m grid and subtracts. A
better anchor uses the official timing sector lines: each lap's distance at its sector-1 and sector-2
times is a fixed physical point on the circuit, so we can warp one lap's distance piecewise to put those
points on the other's. With np.interp, that is a few lines:
def sector_anchor(tel, lap_row, ref_marks):
"""Warp a lap's integrated distance piecewise-linearly so that its sector lines land on ref_marks."""
t1 = lap_row.duration_sector_1
t2 = t1 + lap_row.duration_sector_2
own = [0.0, np.interp(t1, tel.time_s, tel.distance_m), # where this lap was at the S1 line
np.interp(t2, tel.time_s, tel.distance_m), # ... and at the S2 line
tel.distance_m.iloc[-1]]
out = tel.copy()
out["distance_m"] = np.interp(tel.distance_m, own, ref_marks) # piecewise-linear warp
return out, own
_, marks_v = sector_anchor(ver, row_v, [0, 1, 2, 3]) # just to read VER's own marks
nor_a, marks_n = sector_anchor(nor_t, row_n, marks_v) # warp NOR onto VER's marks
anch = telemetry.delta_time(ver, nor_a, normalise=False)
== A.5.3 Idiom: aligning two laps on distance
VER 1:26.983 samples 325 integrated 5789 m
NOR 1:26.995 samples 325 integrated 5777 m
uniform delta at the line: +0.012 s; min -0.258 s at 2900 m; max +0.110 s at 770 m
sector-line distances VER: [2180 4706] NOR: [2178 4698]
sector-anchored delta at the line: +0.012 s; largest difference from uniform: 0.092 s
official sector deltas NOR-VER: S1 -0.029 S2 -0.054 S3 +0.095
resample_on_distance: 1158 rows on a 5 m grid; columns ['distance_m', 'time_s', 'speed', 'rpm', 'throttle', 'x']
Read the output carefully, because it is a lesson in resolution. Each lap has 325 samples over about 87 s, roughly 3.7 per second. The integrated distances (5,789 m and 5,777 m) fall short of the official 5,807 m. Both alignments agree that Norris finished 0.012 s behind, as they must. Inside the lap they disagree by up to 0.092 s, and the uniform version's lowest point, Norris 0.258 s ahead near 2,900 m, is largely an alignment effect in the slow hairpin, where a few metres of misplacement are worth tenths. The official sectors are the ground truth for the coarse split: Norris was 0.029 s up in sector 1 and 0.054 s up in sector 2, and lost 0.095 s in sector 3.
telemetry.resample_on_distance(tel, step_m=5) puts a single lap on a regular 5 m grid, which is what you
want before overlaying speed traces or averaging several laps.
⚠️ Common pitfall: trusting sub-sector deltas. At 300 km/h a car covers about 20 m between samples,
so braking points are located only to within about ±10–20 m. Treat integrated-distance deltas under about
0.05 s, or differences under about 20 m, as noise. Where qualifying location data exist, align on the
circuit's x/y track line for braking-point work; Chapter 7
shows that a uniform alignment made one driver appear to brake later in 73 % of stops, a difference that
vanished on the location-based line. Chapter 19
and Chapter 23 build the full
comparison tools, and Box Box's laptime.delta_trace(align="sectors") packages the sector-anchored version.
📋 Try it: Compare these drivers. Change the script to compare Norris with Piastri in the same session
(Piastri was third, 0.044 s behind pole). Which sector did Piastri lose most in? Does the uniform and
sector-anchored disagreement grow or shrink? Before you trust any lap, check it for frozen telemetry with
boxbox.data.longest_frozen_run_s(tel); anything over 2 s is suspect.
A.5.4 Putting an interval on it
Every number in this book comes with its uncertainty. Two tools cover nearly every case.
The percentile bootstrap, for medians and differences of medians. Resample the data with replacement many times, recompute the statistic each time, and read off the middle 95 % of the results:
x = metrics.fuel_corrected(lp[(lp.acronym == "NOR") & lp.is_clean]).lap_time_fc
est, lo, hi = metrics.bootstrap_ci(x) # returns THREE values: estimate, low, high
rng = np.random.default_rng(42) # the same thing by hand
xa = x.to_numpy()
boots = np.median(xa[rng.integers(0, len(xa), size=(10_000, len(xa)))], axis=1)
np.quantile(boots, [0.025, 0.975])
== A.5.4 Idiom: bootstrap and Wilson intervals
NOR median fuel-corrected clean lap 80.527 s, 95% bootstrap CI [80.260, 80.705], n = 62
by hand: [80.260, 80.705]
NOR - LEC median difference -0.455 s, 95% CI [-0.784, -0.127] (5,000 resamples, seed 42)
car starting from grid slot 1 won 150 of 273 races 2014-2026: 54.9% (Wilson 95% CI 49.0-60.7%)
The hand-made version reproduces the toolkit's interval exactly, because both use seed 42 and the same
resampling scheme. The line xa[rng.integers(0, n, size=(10_000, n))] is the heart of it: a
10,000 × 62 array of random positions, used to index the data, gives 10,000 resampled races at once, and
np.median(..., axis=1) takes each row's median.
For the gap between two drivers, resample each driver separately and take the difference each time. Norris's median fuel-corrected clean lap was 0.455 s quicker than Leclerc's, with a 95 % interval of 0.127 to 0.784 s. The interval excludes zero, so on these laps the pace difference is real, but its size is uncertain by a factor of six from one end to the other. That is a typical result from a single race, and it is why the book pools races wherever it can.
The Wilson interval, for proportions from counts. metrics.wilson_ci(k, n) returns the proportion and
its low and high limits. The example counts how often the car starting from grid slot 1 won, 2014–2026:
150 of 273 races, 54.9 % (49.0–60.7 %). This uses Jolpica's grid, the actual starting grid after
penalties, so it is not the same quantity as "pole position wins", which uses qualifying order; the book's
pole-to-win figures use the latter and so differ slightly. Always say which one you counted.
⚠️ Common pitfall: unpacking two values. lo, hi = metrics.bootstrap_ci(x) fails with "too many
values to unpack": the function returns the estimate first. Write est, lo, hi = ….
⚠️ Common pitfall: bootstrapping correlated laps. Consecutive laps of one driver are not independent (the same tyres, the same traffic), so a lap-level bootstrap is somewhat too narrow. When you compare across races, resample whole races, as Chapter 21's driver ratings do. Appendix E covers the statistics in depth.
A.5.5 History with Jolpica
The history module works the same way, with Jolpica refs (max_verstappen, red_bull, suzuka)
instead of acronyms. Its tables go back to 1950 for results, 1994 for qualifying, 1996 for lap times and
2011 for pit stops.
q = history.qualifying(2025)
q = q.assign(best_s=q[["q1_s", "q2_s", "q3_s"]].min(axis=1)) # best time across the knockout sessions
q[q["round"] == 3].nsmallest(3, "best_s")
history.driver_standings(2025, final=True).sort_values("position").head(3)
history.laps(1996, 1) # lap times from 1996 onward
== A.5.5 Idiom: history with Jolpica
2025 qualifying rows: 479 | qbest_s non-null: 0 | q1_s non-null: 456
abbreviation quali_position q3_s best_s
VER 1.0 86.983 86.983
NOR 2.0 86.995 86.995
PIA 3.0 87.027 87.027
driver_name points position win_count
Lando Norris 423.0 1.0 7
Max Verstappen 421.0 2.0 8
Oscar Piastri 410.0 3.0 7
1996 R1 Jolpica laps: 812 | columns: ['session_type', 'year', 'round', 'race_name', 'circuit_ref', 'driver_ref', 'driver_name', 'abbreviation'] ...
Two lessons hide in this output. First, qbest_s is empty for all of 2025, so a script that used it as
"best qualifying time" would silently get nothing. Compute the best time as the minimum of q1_s, q2_s
and q3_s, as above; min(axis=1) takes the minimum across columns, row by row, skipping NaN. Round 3 is
the Japanese GP, and the top three match the OpenF1 telemetry laps of §A.5.3 to the millisecond.
Second, final=True returns the standings after the last round of the season. The 2025 title went to
Norris by two points over Verstappen. Champions and records in this book are always computed this way,
never typed from memory.
A.6 Errors you will meet, and what they mean
== A.6 Errors you will meet
DataMissingError for session_key 9900 -> no laps rows for session ...
2025 Q sessions listed: 24 | with laps: 23
ValueError: 'United States' is ambiguous in 2026: R4 Miami Grand Prix, R18 United States Grand Prix, R21 Las Vegas Grand Prix (pass
race_control.flag dtype: string | NA values: 49
TypeError: boolean value of NA is ambiguous
safe test: 0 RED rows
tyre_age dtype: Int64 -> for statsmodels use .astype(float)
DataMissingError. The toolkit raises it when a table, session or driver is missing, with a message saying which. The 2025 Azerbaijan GP qualifying session is listed in OpenF1 but has no laps, so any loop over "every 2025 qualifying session" hits it. Filter first withf1data.sessions(2025, "Q")and itshas_lapscolumn (23 of 24 sessions), or wrap the call intry/except f1data.DataMissingError.- Ambiguous session names.
f1data.session()matches GP names by substring, and "United States" in 2026 matches three races. Pass the round number or the Jolpica circuit ref ("americas"). "Qatar" is ambiguous in 2023 and 2025 for the same reason, and"bahrain"in 2026 finds the round held at Sepang, named "Bahrain Grand Prix in Malaysia" in Jolpica. boolean value of NA is ambiguous. Text columns with missing values hold<NA>, and<NA> == "RED"is neither True nor False. Fill first:rc.flag.fillna("").eq("RED"). (This race had no red flag, so the safe test counts zero.)- Nullable integers in models. statsmodels and some scikit-learn functions reject
Int64columns containing<NA>. Cast with.astype(float)before fitting. SettingWithCopyWarning. You filtered a DataFrame and then assigned to a column of the result. Add.copy()after the filter, or use.assign(new_col=…), which always returns a new table.KeyError: 'status'. Jolpica results havestatus_text(and the derivedfinishedflag), notstatus. When a column name surprises you, printdf.columnsor look it up in Appendix B.
A.7 Quick reference
| task | pandas / toolkit |
|---|---|
| one session | f1data.session(2025, "Mexico City", "R") or f1data.session(2025, 20, "R") |
| laps, clean only | f1data.laps(s, clean=True) |
| one driver | f1data.laps(s, driver="NOR") (acronym, car number or Jolpica ref) |
| filter rows | df[(df.a == x) & df.flag], df.query("a == 'x' and flag"), df[df.a.isin([...])] |
| count values | df.col.value_counts(); share of True: df.flag.mean() |
| per group | df.groupby(keys, as_index=False).agg(out=("col", "median")) |
| group value on every row | df.groupby(keys).col.transform("median") |
| join | a.merge(b, on="driver_ref", how="left", validate="one_to_one") |
| nearest-in-time join | pd.merge_asof(a, b, left_on=..., right_on=..., by=..., tolerance=...) |
| wide table | df.pivot_table(index="lap_number", columns="acronym", values="lap_duration") |
| elapsed seconds | (df.date_end - t0).dt.total_seconds() |
| fuel correction | metrics.fuel_corrected(df) (state the assumptions) |
| degradation | metrics.degradation(stint), metrics.degradation_table(s) |
| race pace | metrics.race_pace(s) |
| intervals | est, lo, hi = metrics.bootstrap_ci(x); p, lo, hi = metrics.wilson_ci(k, n) |
| one lap of telemetry | telemetry.fastest_lap_telemetry(s, "VER"), telemetry.lap_telemetry(s, "VER", 16) |
| compare two laps | telemetry.delta_time(ref, cmp) (see the alignment caveat) |
| house chart | plots.use_style(), plots.add_source(fig, f1data.source_note(s)), plots.savefig(fig, DIR, name) |
| history | history.results(year, round), history.qualifying(year), history.laps(year, round) |
| final standings | history.driver_standings(year, final=True) |
🔄 Check your understanding 1. Your degradation slope for a stint is 0.002 s/lap. Before concluding the tyres didn't wear, what two things do you check? 2. Two laps' integrated distances are 5,789 m and 5,777 m on a 5,807 m circuit. Why might a delta trace show a 0.25 s swing in one slow corner that the sector times don't? 3. Why does the book seed every random generator?
Answer
- Whether the lap times were fuel-corrected (raw times hide wear, because the car gets lighter every lap) and how many laps went into the fit, with the confidence interval. A slope near zero from raw lap times is the expected result, not a finding.
- Because the distance axis itself is uncertain. In a slow corner a few metres of misplacement are worth tenths of a second, and uniform rescaling spreads the 12 m difference evenly along the lap instead of where it really arose. Anchoring on the sector lines, or on the location track line, reduces it.
- So that every number printed in the book can be reproduced exactly by any reader, and so that a changed result means a changed input or method, not a different random draw.