57 min read

Aisha Bello's first query against the book's data was meant as a sanity check. She asked the laps table

Chapter 2 — The F1 Data Pipeline: OpenF1, Jolpica, FastF1, and Building Your Analysis Environment

Aisha Bello's first query against the book's data was meant as a sanity check. She asked the laps table a simple question: which race lap, run under a green flag, took the longest? She expected something like a slow lap behind a backmarker, perhaps 110 seconds at a long circuit.

The answer was 2,588.523 seconds. That is 43 minutes and 8.5 seconds for one lap of Suzuka, run by car 11, Sergio Pérez's Red Bull, on lap 14 of the 2023 Japanese Grand Prix. The field's median lap 14 in that race was 118.599 s. The lap's track_status was GREEN. Nothing in the race-control feed says the track was neutralised while it was being run.

"So the data's broken," said Ines Duarte, reading over the shared screen.

"Or it's telling the truth very literally," Aisha said, and started joining tables.

Here is what the other tables in the book's snapshot say about car 11 that afternoon. We will build every one of these joins in this chapter.

2023 JAPANESE GP, CAR 11 (PER): every lap
 lap_number  lap_duration compound  stint  is_pit_in_lap  is_pit_out_lap  pit_lane_s track_status  is_clean  position_end
          1       131.202   MEDIUM      1          False           False         NaN    SC|YELLOW     False             7
          2       161.609   MEDIUM      1           True           False        32.4    SC|YELLOW     False             7
          3       186.858     HARD      2          False            True         NaN           SC     False            18
 ...
         11       100.896     HARD      2          False           False         NaN        GREEN      True            13
         12       121.045     HARD      2           True           False        41.4       YELLOW     False            17
         13       208.286     SOFT      3           True            True      2485.9   VSC|YELLOW     False            19
         14      2588.523     SOFT      4           True            True        30.6        GREEN     False            19
         15       132.535     SOFT      5          False            True         NaN        GREEN     False            19
         16           NaN     <NA>   <NA>          False           False         NaN      UNKNOWN     False          <NA>

The pit table holds a visit with a pit-lane time of 2,485.9 s: the car sat in the pit lane for more than 41 minutes. Then it came out, completed another lap, and pitted again. The race-control feed has two stewards' decisions naming car 11, both 5-second time penalties: one for a safety-car infringement (issued during lap 9) and one for causing a collision (issued during lap 15). It also shows car 11's lap-11 time of 1:40.896 deleted for track limits at Turn 14. Jolpica, the second source, agrees to the millisecond on the lap time (2,588.523 s) and classifies the car 19th with status Retired after 15 laps.

So the "broken" lap is real. A car left the pit lane after a long stop and completed a lap, and the timing system dutifully measured the time between two crossings of the line. The data alone cannot tell you why. A plausible reading, consistent with the timing data, is that the car rejoined to take a penalty before retiring, but the numbers don't prove motive, and this book doesn't guess at it. What the numbers do prove is the lesson of this chapter. Every timing table is literal. It records what happened at the timing line, not what you meant by "a lap". If you compute an average lap time for Pérez that day without cleaning, you get 292.6 seconds over his 15 timed laps, more than two and a half times the field's typical lap. If you feed that lap to a degradation model, one row turns a soft-tyre stint into a 43-minute disaster.

Our clean-lap rule catches this lap: it is both a pit in-lap and a pit out-lap, so it never reaches a model. The rule catches it for the right reason, too. A filter that drops "laps that look slow" would also catch it, but it would catch it by luck, and the same filter would throw away the slow-but-real laps you need. This chapter is about building filters that are right for the right reasons, and about knowing, row by row, where your data came from.

Aisha: Every number in this book traces back to a file on your disk. By the end of this chapter you'll know which file, which script made it, and what that script threw away.

Ines: And whether a 43-minute lap is a bug or a story.

Aisha: Usually it's both.

📊 Analytics Track: This is your core chapter. Read every section, run every script, and do the Part C exercises. Chapters 12–14 and 19–27 assume you can load, filter, join and clean the data the way we do here.

🔧 Engineering Track: Focus on §2.2 (what OpenF1 records), §2.8 (telemetry sampling, distance integration and the channels we don't have) and the Project Checkpoint. Skim §2.3 and §2.7.

🎰 Betting Track: Read §2.1, §2.3 (Jolpica's 77 seasons are your base rates), §2.6 (what "clean" means before you trust any pace number) and §2.7. The telemetry section is optional.

By the end of the chapter you will have:

  • a working analysis environment that loads 268,783 laps and 77 seasons of results in seconds, offline;
  • a mental map of three sources, three layers and the scripts between them;
  • the standard cleaning rules, and the evidence for each one;
  • a set of cross-source checks that found real holes in the archive;
  • Box Box's data layer, boxbox/data.py, which every later chapter loads through.

2.1 The map: three sources, three layers

F1 analytics has a supply problem. Teams record hundreds of channels at high frequency, and none of it is public. What the public gets is the timing feed: the data that drives the timing screens and the TV graphics. It covers lap and sector times, positions, gaps, tyres, pit visits, race-control messages and weather, plus a thinned-out stream of car telemetry. This book uses two free routes to that public data and treats a third as optional.

📐 Definition: OpenF1. A free, open-source API (openf1.org) that archives the F1 timing feed from 2023 onward. It covers laps with sector times and mini-sector codes, stints and compounds, pit-lane visits, race-control messages, weather, positions, intervals, overtakes, results, starting grids, a team-radio index (audio links only), championship standings, and car telemetry (car_data, about 3.7 Hz) and positions (location).

📐 Definition: Jolpica-F1. The community-run successor to the Ergast API, which shut down. It holds race results and grids from 1950, qualifying from 1994, race lap times and running positions from 1996, pit-stop pit-lane durations from 2011, sprint results from 2021, and the championship standings. It has no tyre compounds, no telemetry and no flags.

📐 Definition: FastF1. The best-known Python library for F1 data. Since 2026 its official timing source requires an F1 TV subscription. §2.4 shows how a subscriber uses it and explains why nothing in this book depends on it.

Figure 2.1 shows what each source covers. The two are complementary: Jolpica gives depth (seasons back to 1950), and OpenF1 gives detail (every lap since 2023 with tyres, flags and telemetry).

Coverage of the book's two free sources: Jolpica bars run from 1950, 1994, 1996, 2006, 2011 and 2021 to 2026; OpenF1 bars cover 2023 to 2026 only.

📊 Figure (described): One horizontal bar per kind of data, from its first season in the snapshot to 2026. Jolpica (blue) has results from 1950, qualifying times from 1994 (with Q1/Q2/Q3 splits from 2006), race lap times from 1996, pit stops from 2011 and sprints from 2021. OpenF1 (orange) covers only 2023–2026, but with laps, stints, compounds, race control, weather and telemetry. Long questions ("how often does pole win at Monaco?") go to Jolpica; detailed ones ("how fast did the mediums degrade?") go to OpenF1.

The snapshot in numbers

Everything in this book runs on one data snapshot, taken after the 2026 Las Vegas Grand Prix (round 21 of 23). Script code/01_data_snapshot.py counts it:

SESSIONS BY KIND AND SEASON (OpenF1, testing included)
kind  FP1  FP2  FP3   Q   R  S  SQ  T1  T2  T3
year
2023   22   16   16  22  22  6   6   1   1   1
2024   24   18   18  24  24  6   6   1   1   1
2025   24   18   18  24  24  6   6   1   1   1
2026   21   15   15  21  21  6   6   2   2   2

race laps: 101,949; clean race laps: 84,881 (83.3%)
all laps: 268,783; clean: 150,184 (55.9%)

JOLPICA HISTORY TABLES (data/processed/history)
results             26,335 rows   1950-2026
qualifying          11,430 rows   1994-2026
laps               647,986 rows   1996-2026
pitstops            13,052 rows   2011-2026
driver_standings    37,065 rows   1950-2026
sprint_results         612 rows   2021-2026

Read the session table as a calendar. Each season has six sprint weekends (S and SQ), and those weekends have only one practice session, so there are fewer FP2 and FP3 sessions than races. Testing (T1–T3) appears once a year, twice in 2026, when the new regulations brought two test meetings. The two 2026 rounds still to come, Qatar and Abu Dhabi, are not in the data, so any 2026 total in this book is "after 21 of 23 rounds".

The lap counts already contain the chapter's first lesson. Only 55.9 % of all laps are clean (green, representative laps; §2.6 defines the term exactly), and in races the share is 83.3 %. Practice and qualifying are mostly out-laps, cool-down laps and aborted runs; a race is mostly racing. If you average "all laps", you are averaging a mixture of very different things.

Three layers

The pipeline has three layers, and each one has a script that builds it:

Layer Where Built by What it is
Raw data/raw/openf1/, data/raw/jolpica/ scripts/fetch_openf1.py, the Jolpica CSV download API responses exactly as they arrived: JSON per meeting, gzipped JSON per driver for telemetry; Jolpica's CSV dump
Processed data/processed/openf1/*.parquet, data/processed/history/*.parquet scripts/build_openf1.py, scripts/build_jolpica.py tidy tables with consistent keys, enriched laps (tyre age, flags, gaps, weather, is_clean)
Analysis your code the toolkit/ loaders and project/boxbox/ filtered, joined, cleaned frames for one question

Keep the raw layer forever and never edit it. If the processed layer turns out to have a bug, you fix the build script and rebuild from raw in about a minute. That's the reason for the split: raw is evidence, processed is interpretation. When an interpretation changes (and in this chapter several do), the evidence is still there.

Figure 2.2 shows what the raw OpenF1 archive is made of.

Bar chart of raw archive size by OpenF1 endpoint; intervals is the largest at 368 MB, followed by laps, car_data, location and position.

📊 Figure (described): Size on disk of each raw OpenF1 endpoint, with the number of files. The intervals stream (gap to the leader and to the car ahead, several times a minute for every car) is the largest at 368 MB; laps take 141 MB. The orange bars are telemetry, which is gzipped and was still downloading at the time of writing. The tables you use most (laps, stints, pit, race control) are small. The bulk is high-frequency streams.

Setting up your environment

You need Python 3.11 or later (the book was built on 3.13) and the standard scientific stack. From the book root:

pip install -r requirements.txt     # pandas, numpy, scipy, statsmodels, scikit-learn, matplotlib, pyarrow ...
python -m pytest toolkit/tests -q   # the toolkit's tests run on the real processed data

Every chapter script then starts with the same eight-line header, which puts the book root and the project/ folder on Python's import path:

import sys
from pathlib import Path
sys.stdout.reconfigure(encoding="utf-8")            # accented names print correctly on Windows
BOOK = Path(__file__).resolve().parents[3]          # ...\formula-one-analytics
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 to files, no window
from toolkit import f1data, metrics, plots, telemetry, history

Path(__file__).resolve().parents[3] walks up from code/01_data_snapshot.py through code/, the chapter folder and the part folder to the book root. You will see this header at the top of every script in the book. Appendix A covers Python and pandas from the beginning, and Appendix B lists every column of every table.

🔄 Check your understanding 1. You want the share of Monaco Grands Prix since 1996 won from pole. Which source? 2. You want to know how many laps the 2024 Monaco winner ran on hard tyres. Which source? 3. Why does the book keep the raw JSON files after building the parquet tables?

Answer

  1. Jolpica: it has grids and results back to 1950, and OpenF1 starts in 2023.
  2. OpenF1: only it has stints and compounds. Jolpica has no tyre information at all.
  3. Raw is evidence and processed is interpretation. When a cleaning rule changes (the stint-boundary fix in §2.5 is an example), you rebuild from the untouched raw files instead of downloading again.

2.2 OpenF1: the timing feed, one JSON record at a time

OpenF1 is a REST API. You ask for an endpoint (laps, stints, pit, car_data, …) with filters in the query string, and you get back a JSON list of records. Two keys tie everything together:

📐 Definition: meeting_key and session_key. A meeting is a race weekend (or a test). A session is one track session within it: FP1, qualifying, the race and so on. OpenF1 gives every meeting and every session an integer key. The 2026 Las Vegas meeting is meeting_key 1300, and its race is session_key 11420. Every record carries both, so any two tables can be joined on session_key plus driver_number.

A request for every lap of the Las Vegas weekend looks like this. Don't run it: the book's archive already holds the answer, and the free API's rate limit is shared by everyone who uses it.

# Shown, not run: one request to the OpenF1 API (what scripts/fetch_openf1.py does thousands of times)
import requests
r = requests.get("https://api.openf1.org/v1/laps", params={"meeting_key": 1300}, timeout=120)
laps = r.json()                          # a list of dicts, one per driver per lap

What a response looks like

Script code/02_raw_openf1_json.py opens the archived responses for the 2026 Las Vegas weekend and prints one record from each important endpoint. Here is a lap (shortened: the mini-sector arrays have six, seven and ten entries):

--- laps: one record = one driver, one lap
# came from: GET https://api.openf1.org/v1/laps?meeting_key=1300
{
 "meeting_key": 1300,
 "session_key": 11420,
 "driver_number": 3,
 "lap_number": 20,
 "date_start": "2026-11-22T04:35:23.922000+00:00",
 "duration_sector_1": 49.864,
 "duration_sector_2": 46.042,
 "duration_sector_3": 61.9,
 "i1_speed": 163,
 "i2_speed": 186,
 "is_pit_out_lap": true,
 "lap_duration": 157.806,
 "segments_sector_1": [2064, 2064, 2048, 2048, 2048, 2048],
 ...
 "st_speed": 124
}

This one record carries a lot. date_start is a UTC timestamp, which we'll use to slice telemetry and to check whether a flag overlapped the lap. The three sector times add up to the lap time (49.864 + 46.042 + 61.900 = 157.806 s). i1_speed, i2_speed and st_speed are speeds at two intermediate timing points and at the speed trap, a fixed point usually on the longest straight. The segments_sector_* arrays are the mini-sector colour codes that the TV timing graphics turn into yellow, green and purple blocks. The OpenF1 documentation lists the code table: 2048 is a "yellow" (completed, not a personal best) segment and 2064 a pit-lane segment. This lap is a slow out-lap: car 3 left the pits under the safety car deployed on lap 19, and its first two segments are coded as pit lane.

The other endpoints look like this (each from the same race):

--- stints: one record = one set of tyres
{"meeting_key": 1300, "session_key": 11420, "stint_number": 1, "driver_number": 30,
 "lap_start": 1, "lap_end": 1, "compound": "MEDIUM", "tyre_age_at_start": 0}

--- pit: one record = one pit-lane visit
{"date": "2026-11-22T04:35:10.838000+00:00", "session_key": 11420, "lane_duration": 27.768,
 "meeting_key": 1300, "stop_duration": 8.3, "lap_number": 18, "driver_number": 51, "pit_duration": 27.768}

--- race_control: one record = one message
{"meeting_key": 1300, "session_key": 11420, "date": "2026-11-22T04:34:26+00:00", "driver_number": null,
 "lap_number": 19, "category": "SafetyCar", "flag": null, "scope": null, "sector": null,
 "qualifying_phase": null, "message": "SAFETY CAR DEPLOYED"}

--- intervals: a lapped car's gap arrives as a STRING
{"date": "2026-11-22T04:06:26.993000+00:00", "session_key": 11420, "driver_number": 30,
 "interval": "+1 LAP", "meeting_key": 1300, "gap_to_leader": "+1 LAP"}
intervals gap_to_leader value types in this file: {'float': 21011, 'str': 102, 'NoneType': 53}

Three details matter for everything that follows.

  • Pit times come in flavours. lane_duration (27.768 s here) is the time from the pit-entry line to the pit-exit line. stop_duration (8.3 s) is the stationary time, which OpenF1 populates only occasionally: in 0 % of 2023 stops, rising to 32 % in 2026, according to the toolkit's caveat list. Neither is the pit loss, the time a stop costs you against staying out, which we compute from lap times in Chapter 12.
  • Race control is text. Flags, safety cars, penalties and deleted lap times all arrive as human-written messages. The build script reads them with patterns, and §2.6 shows how much they contain.
  • Types are mixed. The gap of a lapped car is the string "+1 LAP", not a number. In this one file, 102 of 21,166 values are strings and 53 are empty. Code that assumes "gaps are floats" will crash or, worse, silently turn the column into text.

⚠️ Common pitfall: trusting a column's type. pd.DataFrame(records) will happily build a column that mixes floats, strings and None. Its type becomes object, and df.gap_to_leader.mean() either fails or gives nonsense. The build script parses these values into two columns, gap_to_leader (seconds, NaN when lapped) and laps_behind_leader (the N in "+N LAPS"). Whenever you read raw data yourself, check df.dtypes and look at a sample of each column's distinct value types before you compute anything.

Telemetry records

Telemetry is a different shape: one record per sample, not per lap. Here is the fastest sample in car 1's 2026 Las Vegas qualifying file:

--- car_data: one record = one telemetry sample
# came from: GET https://api.openf1.org/v1/car_data?session_key=11416&driver_number=1
{"date": "2026-11-21T04:02:54.926000+00:00", "session_key": 11416, "speed": 343, "driver_number": 1,
 "n_gear": 8, "rpm": 12446, "throttle": 100, "meeting_key": 1300, "brake": 0, "drs": null}

car_data samples for car 1 in the whole session: 17,232; median gap between samples 0.240 s;
distinct brake values [0, 100, 104]; drs values []

--- location: x/y/z sample (11230_1.json.gz, 2026 Australian GP qualifying)
{"date": "2026-03-07T05:05:56.573000+00:00", "session_key": 11230, "meeting_key": 1279,
 "z": 95, "x": 4297, "y": 716, "driver_number": 1}
location samples at exactly x = y = 0 (no fix yet): 3,008 of 21,450

Speed in km/h, engine rpm, gear, throttle in percent, brake, DRS. drs is null throughout: 2026 cars have no DRS (active aero replaced it), so the column is empty for the whole season. The brake channel is not a pressure. It is on/off, and the raw file contains the values 0, 100 and, oddly, 104; the toolkit maps anything above zero to 100. The location file gives x, y and z in OpenF1's track units, and it starts with thousands of samples at exactly (0, 0) before the car's position is fixed. Those are not the car sitting at the origin of the circuit.

How the archive was downloaded

The downloader, scripts/fetch_openf1.py, is 156 lines long, and four ideas in it are worth stealing for any data project.

MIN_GAP = 2.05  # seconds between request starts (OpenF1 free tier: ~30 requests/minute)

def get(url, params, tries=8):
    for attempt in range(tries):
        with _lock:                                   # one clock shared by all worker threads
            wait = _last[0] + MIN_GAP - time.time()
            if wait > 0:
                time.sleep(wait)
            _last[0] = time.time()
        r = requests.get(url, params=params, timeout=120)
        if r.status_code == 200:
            return r.json()
        if r.status_code == 404:                      # OpenF1's way of saying "no results"
            return []
        if r.status_code in (429, 500, 502, 503, 504):
            time.sleep(min(60, 4 * 2 ** attempt)); continue   # back off: 4, 8, 16, 32, 60 s
        if r.status_code == 422:                      # too much data for one query
            return None                               # caller splits the request
  1. Be polite. A shared lock spaces request starts at least 2.05 s apart, even with three worker threads, which keeps the downloader at about 29 requests per minute. The comment records the free-tier limit the script was written for; check the OpenF1 documentation for the current terms before you download anything yourself.
  2. Back off exponentially on rate-limit (429) and server errors.
  3. Split when refused. When a whole meeting is too much for one request (HTTP 422), the script asks session by session, then driver by driver.
  4. Write atomically and resume. Each file is written to name.tmp and renamed when complete, so a crash never leaves half a file. Files that already exist are skipped, so the downloader can be stopped and restarted at will. A 404 becomes an empty list [], which records "OpenF1 had nothing" as a fact.

Those empty lists are informative. Three meetings have an empty laps file, and they are exactly the three OpenF1 marks as cancelled: the 2023 Emilia Romagna GP, and the 2026 Bahrain and Saudi Arabian GPs. Twelve meetings have an empty pit file: those three, the three testing meetings, and the first six rounds of 2023, for which OpenF1 has no pit data. We'll see in §2.5 how the build fills that gap.

The telemetry download is the slow part: one request per driver per session, two for qualifying (speed and position). The downloader orders the queue so that the newest season's qualifying sessions arrive first. That is why, at the time of writing, the telemetry on disk is 2026 qualifying (all 21 sessions, with location), with the 2025 sessions arriving behind it. Telemetry code in this chapter uses 2026 qualifying sessions only.

🔄 Check your understanding 1. A lap record says duration_sector_1 = 31.855, duration_sector_2 = 39.439, duration_sector_3 = 17.484. What is lap_duration? 2. Why does the downloader save [] for a 404 instead of skipping the file? 3. What does "brake": 100 mean, and what does it not mean?

Answer

  1. 31.855 + 39.439 + 17.484 = 88.778 s. (That is the fastest lap of 2026 Japanese GP qualifying, which we meet again in §2.8.)
  2. So that "OpenF1 has nothing for this meeting" is recorded and the resumable downloader doesn't ask again on every restart. The empty files are also a free audit: they line up with cancelled meetings and known gaps.
  3. The brake was applied at that sample. It is not a pressure, a pedal position or a deceleration. Two drivers both showing 100 may be braking very differently.

2.3 Jolpica: seventy-seven seasons in CSV

The Ergast API served historical F1 results to a generation of fans and researchers until it shut down. Jolpica-F1 (github.com/jolpica/jolpica-f1) is its community-run successor. It keeps Ergast's URL scheme and response format, so old code keeps working by changing the host name. FastF1's own historical interface made exactly that switch: in the FastF1 3.9 installed for this book, the Ergast module's base URL is https://api.jolpi.ca/ergast/f1.

Jolpica offers two ways in:

  • The API, which is convenient for one race at a time. Responses are paginated (at most 100 rows per page), so a race's 1,000-plus lap times take a dozen requests.
  • The CSV dump: the whole database as one zip of CSV files, one per database table. For an archive this is far better: one download instead of tens of thousands of requests.

The book uses the dump and tops it up from the API. The dump was dated 9 November 2026, which is before the Las Vegas GP, so scripts/build_jolpica.py asks the API only for the rounds completed since. In the snapshot that was a single round, 2026 R21.

What the build does

The dump is a normalised database: a lap row points to a session entry, which points to a round entry, which points to a team-driver pairing, which points to a driver and a team. build_jolpica.py flattens that chain with merges so that every row of every output table carries the same readable keys:

KEYS = ["year", "round", "race_name", "circuit_ref", "driver_ref", "driver_name", "abbreviation", "team_ref",
        "team_name", "car_number"]

entry = (rentry.merge(tdrv[["team_driver_id", "driver_id", "team_id"]], on="team_driver_id")
         .merge(drivers[["driver_id", "driver_ref", "driver_name", "abbreviation"]], on="driver_id")
         .merge(teams[["team_id", "team_ref", "team_name"]], on="team_id"))

Jolpica stores times as text ('00:01:16.29' for a lap, '02:13:23.6' for a race), so the script has a small parser, td(), that turns them into seconds. Qualifying times live in the lap table, one row per timed lap per part of qualifying; the script takes each driver's best per part and pivots them into columns q1_s, q2_s, q3_s (from 2006, when the three-part format arrived) and qbest_s for earlier single-session formats. Laps marked deleted in Jolpica are excluded from those bests.

The API top-up shows what a Jolpica JSON response looks like. The data sit inside an envelope, MRData → RaceTable → Races → Results, with a total count for paging:

# Shown, not run: the API top-up loop in scripts/build_jolpica.py
def api(path):
    out, off = [], 0
    while True:
        r = requests.get(f"{API}/{path}.json", params={"limit": 100, "offset": off}, timeout=60)
        d = r.json()["MRData"]               # the Ergast-format envelope
        out.append(d)
        off += 100
        if off >= int(d["total"]):           # stop when every page has been fetched
            return out
        time.sleep(0.6)                      # be polite between pages

for p in api(f"{y}/{rnd}/laps"):
    for race in p["RaceTable"]["Races"]:
        for L in race["Laps"]:
            for t in L["Timings"]:           # {"driverId": "...", "position": "1", "time": "1:35.123"}
                ...

Why depth matters

Seventy-seven seasons are the reason Jolpica is in this book. A detailed 2026 analysis tells you what happened. A base rate from 1996–2026 tells you how unusual it was. Ray Castellano, who has watched F1 since the 1980s and places small, careful bets, puts it his own way:

Ray: Four seasons of OpenF1 is four seasons. If a team has had six safety cars at a track in four years, I want to know about the thirty before that.

Aisha: Jolpica has the lap times back to 1996, but no flags.

Ray: So you infer the safety cars from the lap times.

Aisha: The toolkit does, and it tells you how often it's wrong.

That detector, which flags laps where the whole field slowed by more than a threshold, is validated against OpenF1's race-control feed for 2023–2026; Chapter 14 uses it. The pattern generalises: when an old source lacks a variable, infer it, and measure the inference against the new source where they overlap.

⚠️ Common pitfall: reading Jolpica's duration as a pit stop. Jolpica's pit-stop duration_s is the pit-lane time, entry line to exit line, typically over 20 s. It is not the 2-second stationary time you see on TV graphics, and the book's data have no complete source of stationary times. Chapter 34 works with what the data actually measure.


2.4 FastF1: the best-known library, and why this book doesn't depend on it

If you have read F1 analytics online, you have met FastF1. It is a well-designed open-source Python library that wraps the official live-timing archive in a pandas-based API. For years it was the default way in, and it is still excellent. One thing changed: since 2026, the official timing source FastF1 reads requires an F1 TV subscription. FastF1 3.9, the version installed alongside this book, signs in to a Formula 1 account and sends the subscription token with each request to the live-timing server.

If you have a subscription, this is how you would use it. The code is shown, not run, because this book does not assume a subscription:

# Shown, not run: FastF1 3.9 with an F1 TV subscription.
# One-time sign-in from a terminal (stores a token on your machine):
#     python -m fastf1 auth f1tv --authenticate
# or set the environment variables F1_USERNAME and F1_PASSWORD before running Python.
import fastf1

fastf1.Cache.enable_cache("fastf1_cache")            # a local folder; repeat loads come from disk
session = fastf1.get_session(2026, "Las Vegas", "Q")
session.load()                                       # laps, timing, telemetry, weather, messages

lap = session.laps.pick_drivers("ANT").pick_fastest()
tel = lap.get_car_data().add_distance()              # speed, rpm, gear, throttle, brake + distance
quick = session.laps.pick_quicklaps()                # laps within 107% of the session's best lap

FastF1 has real strengths, and you should know them:

  • One object per session. Laps, telemetry, weather and messages hang off session and are already joined. pick_drivers, pick_fastest, pick_wo_box and pick_track_status cover most filtering.
  • Telemetry helpers. add_distance() integrates speed into distance, and FastF1 can merge car data with position data and interpolate between them.
  • Caching built in. enable_cache gives you the raw-layer idea from §2.1 for free.
  • Jolpica access. Its ergast interface now points at Jolpica (§2.3).

So why doesn't this book use it? Because of the promise on its first page: every number comes from data the reader can download free of charge, and the reader can rerun every chart. A subscription requirement breaks that for many readers. Everything FastF1 does for us (laps, stints, flags, telemetry slicing, distance integration), the toolkit does from OpenF1 and Jolpica, and you will see the code. That last point matters on its own: a library that hides the pipeline also hides its decisions. FastF1's pick_quicklaps, for example, keeps laps within 107 % of the session's best lap. Our clean-lap rule uses 107 % of the driver's own stint median. §2.6 shows that the two rules disagree about 8,258 race laps.

If you do have F1 TV, FastF1 is a fine second opinion. Load the same session both ways and compare the lap times; §2.7 shows how to run exactly that kind of cross-check. Appendix J has a side-by-side reference of the three sources.

🔄 Check your understanding 1. Name two things FastF1 gives you that you would otherwise build yourself. 2. FastF1's pick_quicklaps() and this book's clean-lap rule both use "107 %". What is different?

Answer

  1. Any two of: laps and telemetry already joined in one session object; add_distance(); filtering helpers (pick_*); a built-in cache; access to Jolpica history through the same library.
  2. The reference. FastF1 compares every lap with the session's single fastest lap. The book compares each lap with the same driver's median green lap in the same stint, so a slow car's representative laps are kept and a fast car's traffic laps can still be removed.

2.5 From raw to processed: what the build script decides

scripts/build_openf1.py turns about 2,000 raw files into fourteen tidy parquet tables in about a minute. It is 743 lines long, and almost every block in it is a decision about what the data mean. You don't need to read it line by line, but you should know the decisions, because every number in the book inherits them.

Decision 1: which Grand Prix is this?

OpenF1 has its own meeting names; Jolpica has round numbers and race names. The obvious join is on the name. It fails, and the snapshot shows why:

RACES WHOSE OpenF1 MEETING NAME DIFFERS FROM THE JOLPICA RACE NAME
 year  round         meeting_name     location                        gp_name circuit_ref
 2026     16   Bahrain Grand Prix Kuala Lumpur Bahrain Grand Prix in Malaysia      sepang
 2026     20 São Paulo Grand Prix    São Paulo           Brazilian Grand Prix  interlagos

In 2026 the Bahrain round was relocated to Sepang. OpenF1 still calls the meeting "Bahrain Grand Prix", and another OpenF1 meeting with that exact name, at Sakhir, is flagged cancelled. A name join would attach the Sepang race to the wrong weekend, or to two. So the build matches rounds by date: each meeting's race date is compared with Jolpica's round dates, and the nearest round within ±3 days wins. Dates don't get renamed.

Decision 2: who is this driver, and which team?

OpenF1 identifies drivers by car number within a session. Car numbers are not permanent identities. In the snapshot, five race drivers changed number between seasons, including the two best-known swaps:

drivers whose car number changed between seasons (same driver_ref):
year            2023  2024  2025  2026
driver_ref
bearman          NaN  38.0  87.0  87.0
doohan           NaN  61.0   7.0   NaN
lawson          40.0  30.0  30.0  30.0
max_verstappen   1.0   1.0   1.0   3.0
norris           4.0   4.0   4.0   1.0

The build maps every OpenF1 driver to a Jolpica driver_ref in four steps: (1) by season, round and car number, accepted only if the surname agrees; (2) by full name with accents stripped; (3) by the same acronym and surname elsewhere in the season; (4) by a short list of explicit overrides. The override list has five entries. One is "Kimi ANTONELLI", whom Jolpica lists as "Andrea Kimi Antonelli". The other four are FP1-only drivers whom Jolpica doesn't list at all. The result: all 9,605 OpenF1 driver rows are mapped, with 53 distinct drivers across all sessions and 31 across races.

Teams get a vote: for each season and OpenF1 team name, the most common Jolpica team_ref among that team's mapped drivers wins. §2.7 deals with what happens when a team changes its name.

Decision 3: when did each stint really start?

This is the decision with the biggest consequences, and it shows why "fix the build, rebuild from raw" is the right workflow. OpenF1 sometimes starts a new stint on the pit in-lap instead of the out-lap. The build checks every stint start: if the recorded first lap is not an out-lap but the next lap is, it moves the boundary one lap later, so the in-lap stays on the old tyres. It records the original in stints.lap_start_raw and flags the change in stints.boundary_shifted.

Script code/06_stint_boundary_fix.py measures how often the fix fires:

race stint starts (stint 2+) 2023-2026: 3,163; moved from in-lap to out-lap: 396 (12.5%)
                     mean  sum  size
circuit_short_name
Monte Carlo         0.892  132   148
Montreal            0.877  135   154
Melbourne           0.782  129   165
Catalunya           0.000    0   186
Imola               0.000    0    63
...

It isn't random. It is entirely three circuits, Monaco, Montreal and Melbourne, where the timing line sits inside the pit lane, so a car that pits crosses the line in the pit lane. Does an off-by-one lap matter? Here is green-flag pit loss at those three circuits, computed with the fixed boundaries and again with the raw ones (same stops, same reference laps):

GREEN-FLAG PIT LOSS, FIXED vs RAW STINT BOUNDARIES (stops used by metrics.pit_loss)
             stops  shifted  fixed_median  raw_median  pit_lane_median  raw_minus_fixed
circuit
albert_park     42       42         20.91       15.55            18.00            -5.36
monaco          69       69         20.67       18.22            24.32            -2.45
villeneuve      58       57         20.27       17.84            23.90            -2.43

📐 Definition: green-flag pit loss. For one stop, loss = (in-lap + out-lap) − 2 × reference, where the reference is the driver's median clean lap within ±5 laps of the stop. The circuit figure is the median across green-flag, dry, tyre-changing stops. It is not the pit-lane time: it adds the slowdown into the pit lane and the out-lap warm-up, and subtracts the stretch of track the pit lane bypasses. That's why Monaco's loss (20.7 s) is smaller than its median pit-lane time (24.3 s): the pit lane there replaces a slow part of the lap.

With the raw boundaries, the "in-lap" is really the lap before the in-lap, a normal racing lap, and the "out-lap" is really the in-lap. The genuinely slow out-lap drops out of the sum, and the pit loss comes out 5.4 s too small at Albert Park and about 2.4 s too small at Monaco and Montreal.

Left: share of race stint starts moved by the build, by circuit (Monte Carlo 89%, Montreal 88%, Melbourne 78%, all others 0%). Right: median pit loss raw vs fixed at the three circuits.

📊 Figure (described): The left panel shows where OpenF1 starts stints a lap early: at Monaco, Montreal and Melbourne almost always, and nowhere else. The right panel shows the consequence: median green-flag pit loss with the raw stint table (red) and after the build's fix (green). At Albert Park the raw table makes a stop look 5.4 s cheaper than it is.

📋 Try it — Call the pit stop (with bad data). You are on the pit wall at Albert Park. Your driver leads the next car by 18.0 s (an assumed gap for this exercise), and you have a fresh set of tyres you'd like to use. Your pit-loss estimate comes from a colleague's notebook that loaded OpenF1's stint table directly: 15.6 s. Do you pit for free?

Reveal

With the raw table, 18.0 − 15.6 = 2.4 s of margin: the stop looks free. With the fixed boundaries the median loss is 20.9 s (42 green stops, 2023–2026), so you would rejoin about 18.0 − 20.9 = −2.9 s, behind the car you were leading. The data error alone flips the call. The robust habit: before you trust any pit loss, check stints.boundary_shifted for that circuit, and compare your number with the circuit's pit-lane time. A pit loss well below pit-lane time is possible (Monaco shows why), but it should make you look twice.

Decision 4: phantom laps, missing pit data, and timestamps

Three smaller repairs complete the laps table.

  • Phantom final laps. OpenF1 gives the race winner an extra lap N+1 that starts at the chequered flag and has no time. Script 02 counts 50 such records in the raw race and sprint files; the processed table has 0, because the build drops any race lap numbered beyond the winner's lap count.
  • Pit data borrowed from Jolpica. OpenF1 has no pit rows for the first six races of 2023. The build fills race pit stops from Jolpica's pit-lane times (219 rows, pit.source == "jolpica"), and also fills OpenF1 pit rows whose duration is blank when Jolpica has the same driver and lap.
  • Lap end times. OpenF1 gives date_start and lap_duration. The build computes date_end and, for the 0.014 % of laps with no start time, imputes it from the previous lap's end (date_start_imputed records this).

Decision 5: was the track green?

OpenF1 has no per-lap flag column. It has race-control messages. The build turns them into track-status windows: a safety-car window opens at SAFETY CAR DEPLOYED and closes when the leader starts the lap after SAFETY CAR IN THIS LAP; a VSC window closes at the TRACK CLEAR that follows VSC ENDING; a red-flag window runs to the next SESSION STARTED; a yellow runs to the matching CLEAR, capped at 120 s. Any lap whose [date_start, date_end] overlaps a window by any amount gets that status. The toolkit README documents every rule, including the 2026 change of wording from "VIRTUAL SAFETY CAR" to "VSC", which the parser handles. Two more 2026 quirks needed rules of their own. Race control now posts a red flag as a plain message ("RED FLAG - RACE SUSPENDED") with no flag value, so the build reads the message text as well as the flag field. And the first lap a driver completes after a red flag, the standing or rolling restart, is slow but sits under no flag at all; the build marks it RESTART (224 race laps in the snapshot) so it can never pass for green running.

The rule for yellows is deliberately conservative: a yellow in any sector flags the lap for every car whose lap overlaps it. That costs some clean laps, and it's the right trade. A lap that might have been slowed by a yellow is not a lap you want in a pace model.

Decision 6: what was happening at the end of each lap?

Positions, gaps and weather are separate streams with their own timestamps. The build attaches them to laps with an as-of join (pandas.merge_asof): for each lap's date_end, take the most recent position record, the nearest-before interval record within 30 s, and the nearest weather record within 10 minutes. This is the standard way to align event streams that weren't sampled together. You'll use it again for telemetry in §2.8.

Finally, each table is written as name.parquet.tmp and renamed, the same atomic trick as the downloader, so other programs reading the data never see a half-written file.

🔄 Check your understanding 1. Why are rounds matched by date rather than by name? 2. At which three circuits does the stint-boundary fix fire most, and what is the common feature? 3. Monaco's median pit loss (20.6 s) is smaller than its median pit-lane time (24.3 s). How can a stop cost less than the time spent in the pit lane?

Answer

  1. Names change and repeat. In 2026 OpenF1 calls the Sepang race "Bahrain Grand Prix", a name it also gives the cancelled Sakhir meeting. Dates within ±3 days identify the round unambiguously.
  2. Monaco, Montreal and Melbourne (Albert Park), where the timing line lies inside the pit lane.
  3. While a car is in the pit lane it is not driving the stretch of track the pit lane runs alongside. The loss is the extra time compared with a racing lap, so it is pit-lane time minus the time that stretch of track would have taken, plus the slow-in and warm-up costs. At Monaco the bypassed stretch is slow.

2.6 Cleaning: deciding which laps tell the truth

The processed laps table has 268,783 rows. Almost every analysis in this book wants a subset of them: the laps that represent a car's pace. This section builds that subset, rule by rule, and shows the evidence for each rule. Along the way you'll learn the four pandas operations that do 90 % of F1 analysis: load, filter, group, merge.

pandas in four moves

A pandas DataFrame is a table: rows, named columns, and a type for each column. The toolkit loads one for you:

s = f1data.session(2023, "Japanese", "R")      # one row describing the session (a pandas Series)
laps = f1data.laps(s)                          # DataFrame: one row per driver per lap, 50+ columns
laps.shape                                     # (rows, columns)
laps[["acronym", "lap_number", "lap_duration", "track_status"]].head()   # pick columns, first 5 rows

Filtering uses a boolean mask: a column of True/False values, one per row, built with comparisons and combined with & (and), | (or) and ~ (not). Every condition goes in its own parentheses:

green = laps[(laps.track_status == "GREEN") & ~laps.is_pit_in_lap & (laps.lap_number > 1)]

Grouping splits the rows by one or more columns, computes something per group, and stitches the answers together. "Median lap time per driver" is one line:

green.groupby("acronym").lap_duration.median().sort_values()

Merging joins two tables on shared key columns, like a database join. §2.7 is all about merges. With those four moves, here is the book's standard cleaning rule.

📐 Definition: clean lap (is_clean, metrics.clean_laps). A lap is clean (green and representative) when all of these hold: 1. it is not lap 1; 2. it is not a pit in-lap or out-lap; 3. its track status is GREEN for the whole lap (no SC, VSC, red flag or yellow overlaps it, and it isn't the restart lap after a red flag); 4. it has a lap time; 5. its time is at most 107 % of the same driver's median green lap (rules 1–4) in the same stint.

The funnel

Script code/03_cleaning_funnel.py applies the rules in order to every race lap in the snapshot and counts what each one removes:

steps = [("All race laps", pd.Series(True, index=race.index))]
m = pd.Series(True, index=race.index)
for label, cond in [("not lap 1", race.lap_number > 1),
                    ("not a pit in/out lap", ~(race.is_pit_in_lap | race.is_pit_out_lap)),
                    ("green for the whole lap", race.track_status == "GREEN"),
                    ("has a lap time", race.lap_duration.notna()),
                    ("within 107% of stint median", race.is_clean)]:
    m = m & cond                       # each rule narrows the previous mask
    steps.append((label, m.copy()))
CLEAN-LAP FUNNEL, RACE LAPS 2023-2026 (rules applied in order)
                       step   laps  removed  share_left
              All race laps 101949        0       1.000
                  not lap 1 100095     1854       0.982
       not a pit in/out lap  93468     6627       0.917
    green for the whole lap  85369     8099       0.837
             has a lap time  85369        0       0.837
within 107% of stint median  84881      488       0.833

Horizontal funnel of race laps: 101,949 at the top, then 100,095, 93,468, 85,369, 85,369 and 84,881 clean laps.

📊 Figure (described): Race laps remaining after each rule, applied in order. The flag rule removes the most (8,099 laps), followed by pit in/out laps (6,627) and lap 1 (1,854). The 107 % rule, the one people argue about, removes only 488 laps once the structural rules have done their work. 83 % of race laps survive.

Notice what the funnel says about which rules matter. The 107 % threshold gets the attention, but it is the last and smallest step. The structural rules (lap 1, pits, flags) do the real work, and they are reasons, not thresholds: a pit lap is slow because it includes a pit stop. A rule based on a reason removes the right laps whatever the lap time. Pérez's 43-minute lap from the opening of this chapter goes out at step 2.

The "has a lap time" step removes nothing because the flag step has already taken every untimed lap: a lap with no time usually has no timestamps either, so its track status is UNKNOWN, which isn't GREEN. Order matters when you report a funnel; the totals don't.

One messy race, every lap classified

Figure 2.5 shows the rules at work on the race from the hook.

Scatter of every lap of the 2023 Japanese GP, lap time against lap number, coloured by why the lap is or isn't clean; SC and VSC periods shaded.

📊 Figure (described): Every lap of every car in the 2023 Japanese GP. Green dots are the 687 clean laps, a tight band from about 95 to 102 s. Lap 1 (grey squares) and the safety-car laps 2–4 (shaded) sit far above; the VSC on laps 13–14 catches a cluster of laps; orange triangles are pit in- and out-laps, spread well above the racing band. Exactly one lap is removed by the 107 % rule alone (red cross, lap 26). Pérez's lap 14 is off the top of the chart.

2023 JAPANESE GP lap classification: {'clean': 687, 'SC / VSC / yellow': 97, 'pit in/out lap': 80, 'lap 1': 20,
'slow (> 107% of stint median)': 1}

🧩 Productive struggle. Before reading on, look at Figure 2.5 and design your own rule for "laps that show a car's true pace" in this race. Write it down. Then test it on these two cases. (a) A driver with a damaged car runs consistent 106 s laps for ten laps while the field runs 98 s. Are those laps representative? Of what? (b) A leader stuck behind a lapped car loses 1.5 s on one lap. Should that lap count?

One way to think about it

Case (a) is why the 107 % reference is the driver's own stint median, not the session's best lap. The damaged car's laps represent the damaged car's pace, which is exactly what a strategist needs to model that car's race. A session-best rule (FastF1's pick_quicklaps) would throw all ten away. Case (b) is a traffic lap: a 1.5 s loss is well inside 107 %, so it stays clean. That is deliberate. Clean means "green and representative", not "unimpeded". Traffic is part of racing, and Chapter 20 builds the traffic correction as a separate, explicit step rather than hiding it inside the cleaning.

🔍 Why this works: a median reference. The 107 % rule compares each lap with a median, not a mean. A median ignores the extremes: one 2,588-second lap moves a stint's mean enormously and its median not at all. Because the median is taken over laps that already passed rules 1–4, it describes the car's typical green lap on that set of tyres, and 107 % of it allows a lap up to about 6.7 s slower than a 95 s median. Real degradation over a stint (tenths per lap) stays inside the band; incidents, spins and damage stops fall outside. Comparing within the stint matters too: a fresh-tyre stint and a worn-tyre stint each get their own reference, so neither is judged against the other.

The 107 % rule two ways

How different is "107 % of my own stint" from "107 % of the session's best"? On the 85,369 race laps that pass rules 1–4:

107% RULE TWO WAYS (green, timed, non-pit race laps from lap 2)
candidate laps: 85,369
kept by toolkit rule (<= 107% of the driver's median in that stint): 84,881 (99.4%)
kept by 'session best x 1.07' rule: 76,623 (89.8%)
fast_107_session  False  True
is_clean
False               488      0
True               8258  76623
dropped only by the session-best rule: 8,258; by cars classified P11 or lower: 64%; in the first half of the race: 70% (all clean laps: 49%)

Every lap the session-best rule keeps, the toolkit rule keeps too. But the session-best rule throws away 8,258 laps the toolkit rule keeps. They come mostly from the back of the field and from early in the race: 64 % were driven by cars that finished 11th or lower, and 70 % fall in the first half of the race distance (against 49 % of all clean laps). Heavy fuel and a slower car can put a perfectly representative lap more than 7 % off the race's fastest lap. If your question is "how fast was the Sauber on old hards?", the session-best rule deletes your answer. The number "107 %" is borrowed from the qualifying rule in the FIA Sporting Regulations, which uses it as a cut-off against the fastest Q1 time. The threshold is borrowed; the reference is ours, because our question is different.

Lap 1, nulls and red flags

Some laps have no time at all, and how often depends on the session:

SHARE OF LAPS WITH NO lap_duration, BY SESSION KIND
FP1 0.054   FP2 0.054   FP3 0.069   Q 0.095   SQ 0.123   R 0.003   S 0.005
race+sprint lap 1 null share: 0.048 (n=2,344); race lap 1 only: 0.050
laps with track_status UNKNOWN (no timestamps): 1.109%; date_start imputed: 0.014%

In qualifying, about one lap in ten has no time: aborted runs and laps the timing didn't close. In races, it is three in a thousand, and they cluster on lap 1. Lap 1 is excluded from clean laps anyway (a standing start, cold tyres, a full field in one corner), but it's worth knowing the gaps are there before you compute anything about starts. Chapter 17 works with lap-1 positions, which Jolpica records even where OpenF1 has no lap-1 time.

Red flags make the longest laps in the archive:

LONGEST RACE LAPS OF ALL
 year             gp_name acronym  lap_number  lap_duration track_status
 2023    Dutch Grand Prix     VER          65      2625.541          RED
 2023    Dutch Grand Prix     ALO          65      2595.634          RED
 2023 Japanese Grand Prix     PER          14      2588.523        GREEN
 2023    Dutch Grand Prix     GAS          65      2579.227          RED
 2023    Dutch Grand Prix     SAI          65      2577.121          RED
race laps longer than 10 minutes: 210 in 13 races

When a race is stopped, the lap containing the stoppage includes the whole suspension: 43 minutes and 45.5 seconds for Verstappen's lap 65 at Zandvoort in 2023. Those laps carry the RED status, so the flag rule removes them. The restart lap after a red flag is slow without being neutralised (a standing or rolling restart), so the build gives it its own status, RESTART, and the flag rule removes it too. The toolkit's caveats list one case, the 2024 Japanese GP, where a red flag on lap 1 left OpenF1's lap-1 timestamps wrong. Cases like these are why a cleaning rule is never finished: you check the extremes every time.

Deleted laps

When a driver exceeds track limits, race control deletes the lap time, and the timing feed announces it as text:

CAR 11 (PER) TIME 1:40.896 DELETED - TRACK LIMITS AT TURN 14 LAP 11 14:25:51
CAR 18 (STR) LAP DELETED - TRACK LIMITS AT TURN 1 LAP 42 18:05:33 (PIT)

The laps table has no "deleted" column, so we parse the messages with a regular expression, a pattern that matches text and captures its parts (car number, acronym, time, reason, turn, lap):

pat = (r"CAR (?P<car>\d+)(?: \((?P[A-Z]{3})\))? (?:TIME (?P<time>[\d:.]+) DELETED|LAP DELETED)"
       r" - (?P<reason>[A-Z ]+?)(?: AT TURN (?P<turn>\d+))?(?: LAP (?P<lap>\d+))?(?: \d\d:\d\d:\d\d)?(?: \(PIT\))?$")
ext = deleted_msgs.message.str.extract(pat)        # one column per named group
DELETED-LAP MESSAGES: 3,971; parsed by the pattern: 3,779
reason: {'TRACK LIMITS': 3590, 'DOUBLE YELLOW': 185, 'TRACK LIMITS AT PIT ENTRY': 4}
race deletions with a lap number: 1,416; matched to a lap row: 1,410; of those still is_clean=True: 1,106
message time equals that lap's lap_duration (within 0.0015 s): 99.9% of 1,323

Two findings. First, the parse is trustworthy: where a message gives both a lap number and a time, the time equals that driver's lap_duration on that lap in 99.9 % of 1,323 cases. Second, 1,106 deleted race laps are still marked clean. Is that a bug? No. In a race, a deleted lap still happened. The car still covered the distance at that pace, and its tyres still aged, so it represents race pace. In qualifying, a deleted lap doesn't count for the grid, and an analysis of "who was fastest" must drop it. That is why the Box Box data layer offers clean_laps(exclude_deleted=True) as an option rather than a default. The right rule depends on the question.

Grouped bars of race-control 'DELETED' messages by session type and season; practice sessions have almost none before 2026 and hundreds in 2026.

📊 Figure (described): Deleted-lap messages per session type and season. Qualifying, sprint and race counts are similar every year. Practice is the outlier: almost nothing in 2023–2025 (29 messages in all of 2023 FP1, none in FP2 or FP3), then 521, 456 and 314 in 2026 FP1, FP2 and FP3. The feed changed what it reports, so a "track-limits trend" across those years would be a reporting artefact, not a driving one.

📺 On the broadcast: When the TV graphic says a driver's lap time has been deleted, this is the same message reaching you. In qualifying the commentators will often say "that lap won't count". In the data, the lap row is still there with its time, and only the race-control message tells you it didn't count. If you rebuild a qualifying classification from lap times alone, you will sometimes put a driver on a grid slot the stewards took away.

Sprints, testing and the fastest lap that wasn't pole

Three more traps:

  • Sprint weekends (six per season in the snapshot) have one practice session, a sprint-qualifying session (SQ), a sprint (S) and the usual qualifying and race. The 2023 format put qualifying on Friday; from 2024 sprint qualifying moved to Friday. Always filter by kind, never by "the second session of the weekend".
  • Testing has 18,724 laps over 15 days in the snapshot, with no telemetry, and 6.5 % of testing laps have a missing or TEST_UNKNOWN compound. f1data.sessions() excludes testing unless you pass include_testing=True: by default it lists 455 of the 470 sessions.
  • The session's fastest lap is not always pole. In 20 of the 21 qualifying sessions of 2026, the fastest timed lap in the laps table is the pole time. The exception is the wet 2026 Brazilian GP qualifying: Russell's 1:26.745 came in Q2, while the grid order comes from Q3, where Norris's 1:27.470 was fastest.

⚠️ Common pitfall: min() is not a classification. laps.lap_duration.min() gives the fastest lap of a session, not the pole position. Qualifying is three sessions in one, laps can be deleted, and the grid can be changed by penalties after the session. For classification, use the results table (f1data.results for OpenF1's order, jolpica_grid for the actual starting grid).

🔄 Check your understanding 1. Which cleaning rule removes the most race laps, and which removes the fewest (apart from "has a lap time")? 2. Why are 1,106 deleted race laps still clean, and when should you remove them? 3. A colleague says, "Just use laps within 107 % of the fastest lap." Give one specific kind of lap this discards that you'd want to keep.

Answer

  1. "Green for the whole lap" removes the most (8,099); the 107 % rule removes the fewest among the rules that remove anything (488).
  2. In a race the lap was still driven at that pace on those tyres, so it represents race pace. Remove deletions when the question is about legal lap times, as in qualifying classifications.
  3. Representative laps of slower cars or heavy-fuel stints, for example a back-marker's consistent laps more than 7 % off the race's fastest lap. Across 2023–2026 races, the session-best rule drops 8,258 laps that the stint-median rule keeps.

2.7 Joins: making two sources agree

Two independent sources recording the same race is a gift. Where they agree, you can trust both; where they disagree, one of them has a problem, and you have found it before it found you. This section joins OpenF1 and Jolpica lap by lap and reads the disagreements.

Keys first

A join (pd.merge) lines up rows from two tables that share key values. The keys must mean the same thing in both tables. For laps, the natural key is (season, round, driver, lap number). The build already gave OpenF1 rows Jolpica's round (matched by date) and driver_ref (matched by number and name), so the merge is direct:

o = f1data.laps(kind="R")[["year", "round", "driver_ref", "acronym", "lap_number", "lap_duration",
                           "position_end", "track_status"]]
j = history.table("laps")                      # every Jolpica lap, 1996-2026
j = j[(j.session_type == "R") & (j.year >= 2023)][["year", "round", "driver_ref", "lap", "lap_time_s", "position"]]
j = j.rename(columns={"lap": "lap_number", "position": "jolpica_pos"})
m = o.merge(j, on=["year", "round", "driver_ref", "lap_number"], how="outer", indicator=True)

how="outer" keeps rows found in either table, and indicator=True adds a _merge column that says where each row came from: both, left_only (OpenF1 only) or right_only (Jolpica only). Always run your first join this way. An inner join silently drops every row that doesn't match, and the rows that don't match are exactly the ones you need to see.

Do the lap times agree?

RACE LAP ROWS, OpenF1 vs Jolpica (2023-2026 R21)
both          101688
right_only       453
left_only        261
matched laps with both times: 101,637
  |difference| <= 0.0005 s: 98.2585%
  |difference| <= 1.0000 s: 99.9744%
lap 1 only: exact 0.0% of 1,761; median OpenF1 - Jolpica = +0.389 s (IQR +0.351 to +0.446)
laps 2+: exact 99.991% of 99,876; differ by > 1 s: 4

Bar chart (log scale) of absolute lap-time differences between OpenF1 and Jolpica: 99,867 laps agree exactly, 1,744 differ by 0.1–1 s, 17 by 1–10 s and 9 by more than 10 s.

📊 Figure (described): For 101,637 race laps present in both sources, the absolute difference between OpenF1's and Jolpica's lap time, on a log scale. Nearly all agree to the millisecond. There is nothing between 1 ms and 0.1 s, which tells you the two sources share an underlying timing record rather than measuring independently. The 1,744 laps in the 0.1–1 s bin are almost all lap 1.

The structure of the disagreement is the finding. From lap 2 on, the sources agree exactly on 99.991 % of laps. On lap 1 they never agree exactly: OpenF1's lap 1 is a median 0.389 s longer than Jolpica's. The two sources start the lap-1 clock at different moments. A standing start has no "previous crossing of the line", so each source has to pick a reference, and they picked different ones. Neither is wrong, but if you compute a race time by summing OpenF1 laps and compare it with Jolpica's, you will be about 0.4 s apart for no racing reason.

The few large differences cluster at unusual moments: a 2024 Japanese GP lap 2 (the lap-1 red flag from §2.6) where Jolpica includes the 28-minute suspension and OpenF1 does not, and a handful of 2025 Miami lap 1s, and one lap at the 2026 Dutch GP. Positions agree as well as lap times: OpenF1's position_end equals Jolpica's lap position on 99.73 % of 101,669 laps, and the final classification agrees on 100 % of 1,621 classified finishers. OpenF1 leaves position empty for 238 race results (retirements and disqualifications), and Jolpica classifies every one of them, which is why the results table carries both columns.

Holes

The 453 Jolpica-only rows are the other finding. Seven come from the 2023 Italian GP. The other 446 come from one race:

races where OpenF1 has under 98% of Jolpica's timed laps:
            openf1  jolpica    share
year round
2025 6.0       556     1002  0.55489

The 2025 Miami Grand Prix in OpenF1 has no lap rows at all for laps 2–24, and only half the field for lap 25. Jolpica has the whole race. Nothing in the OpenF1 tables says the laps are missing: a query for "Piastri's laps in Miami" simply returns 33 rows instead of 57. Only the cross-check reveals it. Case Study 1 rebuilds that race from the two sources, and along the way shows a bug that an early version of the book's own build had: on sprint weekends it mixed the sprint's stops in with the race's. Cross-checks catch your own bugs too.

📋 Try it — Analyze this session: 2024 Monaco Grand Prix. The Box Box coverage check (Project Checkpoint below) reports 16 laps "missing" from OpenF1 for this race, compared with Jolpica. Load it with RaceData.load(2024, "Monaco", "R"), run .coverage() and .laps[laps.lap_duration.isna()], and explain the gap before you open the answer.

Reveal

All 20 OpenF1 lap-1 rows have no lap time. The race was red-flagged on lap 1 (the track-status windows contain one RED window starting on lap 1), and Jolpica's lap-1 times for the 16 cars that took the restart have a median of 2,491.7 s: they include the whole stoppage. The other four cars (OCO, PER, HUL, MAG) are classified with zero laps and have no Jolpica lap at all. So the 16 "missing" laps are not a data hole. They are lap 1s that one source timed through a red flag and the other declined to time. Your analysis should exclude lap 1 either way.

Teams that change their names

Jolpica gives a team a new team_ref when it rebrands. Here are the race entries for 2023–2026, grouped by Jolpica team ref:

TEAM NAMES BY SEASON (OpenF1 team_name, grouped by Jolpica team_ref)
year                     2023             2024             2025             2026
alfa               Alfa Romeo             <NA>             <NA>             <NA>
alphatauri         AlphaTauri             <NA>             <NA>             <NA>
audi                     <NA>             <NA>             <NA>             Audi
cadillac                 <NA>             <NA>             <NA>         Cadillac
rb                       <NA>               RB     Racing Bulls     Racing Bulls
sauber                   <NA>      Kick Sauber      Kick Sauber             <NA>
...

The Faenza team appears as alphatauri in 2023 and rb from 2024; the Hinwil team is alfa, then sauber, then audi. For a question about a team's development across seasons, that's three teams when you want one. For a question about a brand, it's right. Box Box therefore keeps the Jolpica ref and adds a lineage id (team_lineage("alphatauri") == team_lineage("rb") == "faenza") as a separate, explicit column. Don't overwrite the source's identifiers: add your interpretation next to them.

The same issue hides in the book's own reference tables. data/reference/circuits_2023_2026.csv uses circuit ids such as montreal, cota and las_vegas, where Jolpica uses villeneuve, americas and vegas. Six of the circuits differ. Script 05 carries a six-entry mapping to join them. Every time you bring in a new table, check its keys against the ones you already have before you merge.

⚠️ Common pitfall: joining on names. Names are for people; keys are for joins. Grand Prix names change (the 2026 Sepang race), team names change (four rebrands in four seasons), driver numbers change (Norris took number 1 for 2026 and Verstappen moved to 3), and accents come and go ("Pérez" in Jolpica, "PEREZ" in broadcast names). Join on stable ids (session_key, driver_ref, dates), and when you must match on text, normalise it first and check every unmatched row by hand.

🔄 Check your understanding 1. Why run the first join of two sources with how="outer", indicator=True? 2. OpenF1 and Jolpica agree exactly on 99.991 % of laps from lap 2 onward but on 0 % of lap 1s. What does that tell you? 3. You want AlphaTauri's and RB's combined points across 2023–2026. What do you join on?

Answer

  1. To see the rows that don't match. An inner join drops them silently, and unmatched rows are where the holes and key problems are (such as the 446 missing 2025 Miami laps).
  2. The sources share one underlying timing record (otherwise they'd differ by milliseconds everywhere), but they define the start of lap 1 differently, by a median of 0.389 s.
  3. A lineage id that maps alphatauri and rb to one team (Box Box's team_lineage), joined on season, round and driver; not the team name, which changed.

2.8 Telemetry: sampling, distance, alignment and the channels we don't have

Telemetry is the most seductive data in the archive and the easiest to over-read. Teams log their cars at hundreds or thousands of samples per second on hundreds of channels. The public car_data stream has six channels at about four samples per second. This section measures exactly what that means.

How often is a sample?

Script code/05_telemetry_pipeline.py reads every 2026 qualifying file on disk (462 driver files, 8,577,844 samples) and measures the time between consecutive samples:

sample interval (s): p5 0.160, p25 0.200, median 0.240, p75 0.320, p95 0.440; mean rate 3.74 Hz; median rate 4.17 Hz
intervals longer than 0.5 s: 1.04%

Histogram of time between telemetry samples: spikes at 0.16, 0.20, 0.24, 0.28 s and so on, with the median at 0.240 s.

📊 Figure (described): The interval between consecutive car_data samples across all 2026 qualifying files. The intervals cluster in spikes 0.04 s apart (0.16, 0.20, 0.24, 0.28 s …), so the stream is not a steady clock: samples arrive on a 0.04 s grid with irregular gaps. The median is 0.240 s, and the mean rate is 3.74 samples per second. About 1 % of gaps exceed half a second.

At 300 km/h a car covers 83 m every second, so a quarter-second gap is about 21 m of track. On the 2026 fastest qualifying laps, the median distance between samples above 300 km/h was 23.6 m. That is the resolution of every braking point, turn-in point and throttle application you will read from this data: about a car length times five. When Chapter 23 compares braking points, it reports differences smaller than that resolution as "not resolvable", and so should you.

Distance is integrated, not measured

The stream has no distance channel. We compute it by integrating speed over time with the trapezoid rule:

$$d_n = \sum_{i=1}^{n} \frac{v_{i-1} + v_i}{2}\,(t_i - t_{i-1}), \qquad v \text{ in m/s} = \frac{v_\text{km/h}}{3.6}$$

In words: between two samples, assume the car travelled at the average of the two speeds, and add up those little distances. Worked example: two samples 0.24 s apart at 300 and 306 km/h give $\frac{(83.33 + 85.00)}{2} \times 0.24 = 20.2$ m.

How good is that? We can check it against the official lap lengths in data/reference/circuits_2023_2026.csv (from formula1.com event pages), using the fastest lap of each 2026 qualifying session:

integrated - official, all 21: median -0.94%, range -7.22% to +1.56%
integrated - official, 19 laps without frozen telemetry: median -0.94%, range -1.91% to -0.45%
suspect fastest laps (frozen > 2 s): [['Suzuka', 'ANT', 24.65, -7.22], ['Monza', 'GAS', 4.68, 1.56]]

Bar chart of integrated lap distance minus official length for each 2026 qualifying session's fastest lap; most bars between -0.45% and -1.91%, with Suzuka at -7.22% and Monza at +1.56% in red.

📊 Figure (described): For each 2026 qualifying session's fastest lap, the integrated distance minus the official lap length, as a percentage. Nineteen circuits sit between −0.45 % and −1.91 % (median −0.94 %): integration runs consistently about 1 % short. Two bars, in red, are far outside that band: Suzuka (−7.22 %) and Monza (+1.56 %). They are not integration error. They are broken telemetry, and the next subsection shows how to detect them.

The consistent ~1 % shortfall has more than one plausible contributor. The official length is a nominal figure for the circuit, while a car on a qualifying lap takes the racing line, which cuts every corner; and the speed channel is reported in whole km/h. The data can't separate those contributions, and you don't need to: when we compare two laps, telemetry.delta_time rescales both to the same length by default, which removes the drift.

Frozen feeds

Here are the two outliers. The Suzuka lap is Antonelli's 1:28.778, the fastest lap of 2026 Japanese GP qualifying:

Speed against time for Antonelli's and Piastri's fastest laps in 2026 Japanese GP qualifying; Antonelli's trace is flat at 189 km/h for the final 25 seconds while Piastri's continues through the last corners.

📊 Figure (described): Antonelli's fastest lap (orange, with sample markers) tracks Piastri's (blue) for 62 seconds, then flat-lines at 189 km/h for the rest of the lap, while Piastri accelerates to over 320 km/h and brakes for the final chicane. For 24.7 s every channel (speed, rpm, throttle and gear) repeats the same value. The feed stalled and kept re-sending its last sample. The lap time, from the timing loops, is unaffected.

A car doing 189 km/h for 25 seconds at exactly the same rpm, in the same gear, at the same throttle, is not driving. So the test for a stalled feed is simple: find runs where all four channels are unchanged from sample to sample while the car is moving.

def longest_frozen_run_s(tel, min_speed=30):
    same = (tel[["speed", "rpm", "throttle", "n_gear"]].astype(float).diff().abs().sum(axis=1) == 0) \
        & (tel.speed > min_speed)
    run_id = (~same).cumsum()                     # a new id every time any value changes
    spans = tel.time_s.groupby(run_id).agg(lambda x: x.iloc[-1] - x.iloc[0])
    return float(spans.max())

The trick in the middle is worth learning. (~same).cumsum() gives every unbroken run of identical samples its own id, because the counter only increases when something changes. Grouping by that id and measuring each group's time span finds the longest run. Applied to every driver's fastest 2026 qualifying lap:

FROZEN TELEMETRY on each driver's fastest 2026 qualifying lap (n = 459 laps)
  longest frozen run > 1 s: 60 laps (13.1%)
  longest frozen run > 2 s: 43 laps (9.4%)
  longest frozen run > 5 s: 14 laps (3.1%)
  laps > 2 s by circuit: {'Suzuka': 17, 'Shanghai': 11, 'Las Vegas': 5, 'Monza': 5, 'Singapore': 3,
  'Interlagos': 1, 'Baku': 1}
  median longest run: 0.24 s

A typical lap's longest frozen run is one sample interval (0.24 s), which happens naturally at a steady top speed. But 9.4 % of fastest laps have a frozen stretch longer than 2 s, and the problem is concentrated: 17 of the 22 Suzuka laps. Any analysis of 2026 Suzuka qualifying telemetry has to check this first, and the Box Box data layer ships the check (longest_frozen_run_s).

⚠️ Common pitfall: plotting before checking. A frozen stretch doesn't crash your code. It integrates into a distance that is 7 % short, it puts a corner 400 m in the wrong place, and it produces a delta trace that says one driver lost 20 seconds in the last sector of a pole lap. Always plot the raw trace against time first, and run the frozen-run check, before you align laps on distance.

Speed traps and sampled top speed

On the same 21 fastest laps, the highest sampled speed is above the speed-trap reading (st_speed, from a timing loop) on every lap, by a median of +13 km/h (range +3 to +44). That doesn't mean either is wrong. The speed trap sits at one fixed point, which is not always where a car reaches its maximum. The sampled maximum is wherever the highest of the ~4 samples per second fell. For "top speed", use the sampled maximum and say so; for comparing cars at the same point, use the trap.

Alignment: time or distance?

To compare two laps, you must line them up. The tempting axis is time since the lap started. It is the wrong one. Figure 2.10 shows why, with the two fastest laps of 2026 Las Vegas GP qualifying: Antonelli's 1:33.893 and Verstappen's 1:34.151.

LAS VEGAS 2026 Q: ANT lap 25 93.893 s, VER lap 17 94.151 s; samples 350 vs 360
integrated lengths: ANT 6150 m, VER 6158 m; final delta +0.258 s
top sampled speed: ANT 351 km/h at t=66.53 s / 4057 m; VER 340 km/h at t=65.22 s / 3989 m
  delta at 1500 m: -0.125 s
  delta at 3000 m: -0.423 s
  delta at 4500 m: -0.274 s
  delta at 6000 m: +0.185 s

Three panels: speed against time for ANT and VER, drifting apart; speed against distance, lined up; and the time delta of VER relative to ANT against distance.

📊 Figure (described): Top: speed against time since the lap started. The corners drift apart, because the driver who is ahead on the road reaches each corner earlier in time. Middle: speed against integrated distance (Verstappen's lap rescaled to Antonelli's length). The corners line up, and differences in speed at the same place become visible. Bottom: the time gap, Verstappen minus Antonelli, along the lap. Verstappen is up to about 0.7 s ahead around 3,300 m, then loses it all and more on the long straight, where Antonelli's sampled top speed is 351 km/h against 340.

The delta trace is the payoff of distance alignment:

$$\Delta t(d) = t_\text{cmp}(d) - t_\text{ref}(d)$$

In words: at each point $d$ along the lap, how much later did the comparison car get there than the reference car? We interpolate each lap's elapsed time onto a common 5 m distance grid and subtract. Positive means the comparison car is behind. The final value equals the lap-time difference: +0.258 s here. Where along the lap the time moved, and why, is the subject of Chapter 19 and Chapter 23. Here the point is mechanical: compare laps on distance, never on time.

Location: drawing the circuit

Qualifying sessions also have location (x, y, z). Merged onto the car data by nearest timestamp (within 0.5 s), it draws the track:

Track map of Monaco from the 2026 pole lap, coloured by speed from about 44 to 290 km/h, with nine speed minima numbered.

📊 Figure (described): Antonelli's 2026 Monaco pole lap (1:12.051) drawn from the location stream and coloured by speed, from 44 km/h at the slowest sampled point to 289 km/h at the fastest. The numbers mark the nine speed minima the toolkit finds with a 20 km/h prominence threshold. They are not the official turn numbers: fast kinks with little speed loss don't register.

MONACO 2026 Q: ANT lap 27 72.051 s; car_data samples 269; with x/y merged: 269
x/y path length 32,702 units vs integrated distance 3,273 m -> ratio 9.99 (decimetre units)

The x/y path is 9.99 times the integrated distance, which confirms the units: OpenF1's coordinates are decimetres. And recall from §2.2 that each location file begins with samples at exactly (0, 0) before the car's position is fixed. Drop them before you draw anything.

What we don't have

Be precise about the limits. They are part of the lesson, and later chapters return to them constantly.

Channel Teams have Our data What we do instead
Speed, rpm, gear, throttle high-rate, many sensors ~3.7 Hz, one value each use as is; state the resolution
Brake pressure, temperature, bias on/off (0/100) only brake zones and entry speeds, not force
Steering angle yes none infer cornering from speed minima and curvature of x/y
Lateral/longitudinal g yes none differentiate speed (noisy); v²/r from track curvature
Tyre temperatures and pressures yes none infer from lap-time behaviour (Ch 4, 22)
ERS / battery state yes none infer deployment from speed traces, with care (Ch 6, 29)
Fuel load yes none fuel-correction model (Ch 20)
Ride height, suspension yes none qualitative only (Ch 8)
Distance measured integrated from speed (~1 % short) normalise laps to equal length
Practice telemetry yes none in our archive practice lap times only

Whenever a later chapter needs one of the "none" channels, it says so, and it either infers the quantity from what we have, labelled as an inference, or uses an illustrative model with stated assumptions.

🔄 Check your understanding 1. At 250 km/h with samples 0.24 s apart, how far does the car travel between samples? 2. Two laps integrate to 6,150 m and 6,158 m. Why rescale before computing a delta, and what would go wrong if you didn't? 3. A delta trace shows a driver losing 2 s in one corner on a pole lap. What do you check first?

Answer

  1. 250 / 3.6 = 69.4 m/s × 0.24 s = 16.7 m.
  2. The two integrations drift by different amounts. Without rescaling, the same corner sits at slightly different distances on the two laps, and the delta picks up a spurious trend that grows along the lap.
  3. Frozen telemetry: plot both raw traces against time and run longest_frozen_run_s. A 2 s loss in one corner on a pole lap is far more likely to be a stalled feed than a real mistake.

Project Checkpoint: boxbox/data.py

Aisha's first module for Box Box is deliberately unglamorous. Every later module (tyre models, pit-loss estimates, the race simulator) needs the same thing first: one object that holds everything we know about a session, already checked. That object is RaceData.

from boxbox.data import RaceData, longest_frozen_run_s, team_lineage

lv = RaceData.load(2026, "Las Vegas", "R")     # round number, circuit_ref or name substring
lv.laps, lv.stints, lv.pits, lv.flags, lv.race_control, lv.weather, lv.results   # DataFrames
lv.clean_laps()                                 # the standard clean laps (toolkit is_clean)
lv.clean_laps(exclude_deleted=True)             # ... minus laps race control deleted
lv.coverage()                                   # OpenF1 vs Jolpica lap counts per driver
lv.summary()                                    # headline facts, as a dict

The module adds four things on top of the toolkit loaders, each from this chapter: deleted_laps() (the race-control parser from §2.6), coverage() (the cross-source check from §2.7), longest_frozen_run_s() (the stalled-feed test from §2.8) and team_lineage() (stable team ids across rebrands). It never redefines a toolkit definition: clean_laps() returns the toolkit's is_clean laps, and the deleted-lap filter is an explicit option. The demo, code/project_checkpoint.py, loads three sessions:

RaceData(2026 Las Vegas Grand Prix, Race: 989 laps, 22 drivers, 23 pit rows, 26 track-status windows)
  leader_laps          50
  clean_laps           781
  clean_share          0.79
  null_lap_times       5
  sc_periods           1
  sc_laps              7
  pit_stops            23
  deleted_laps         16
  rain                 False
  track_temp_c         (13.1, 16.3)
  compounds            ['MEDIUM', 'SOFT']
  winner               VER
  openf1_missing_laps  1

RaceData(2025 Miami Grand Prix, Race: 559 laps, 19 drivers, 18 pit rows, 16 track-status windows)
driver_ref acronym  openf1_rows  openf1_timed  jolpica_timed  classified_laps  missing_vs_jolpica
     albon     ALB           33            33             57             57.0                  24
    alonso     ALO           33            33             56             56.0                  23
OpenF1 laps missing vs Jolpica, whole race: 446

2023 Japanese Grand Prix, Race: 15 deleted laps; clean laps 687, clean laps excluding deletions 671
neutralised laps: {'SC': [1, 2, 3, 4], 'VSC': [13, 14], 'RED': []}
2026 Japanese Grand Prix, Qualifying ANT fastest lap 88.778 s: longest frozen run 24.7 s

Read the Las Vegas summary the way a strategist would before a debrief: a 50-lap race, one safety-car period covering seven laps, a two-compound race (MEDIUM and SOFT), 79 % clean laps, and a winner. Notice that track_temp_c starts at 13.1 °C. The raw weather stream for that race contains a 0.0 °C track reading, one of 44 such zero readings in the whole archive, nearly all in late 2026; the summary treats zeros as sensor dropouts, and says so in the code. The Miami summary flags 446 missing laps before any analysis starts. That is the point of the module: the checks run every time, not when you remember them.

In later chapters, RaceData is the natural entry point: a tyre model fits stints from clean_laps(), a strategy optimiser needs the compounds and pit stops, a safety-car model reads flags, and the capstone in Chapter 40 assembles the modules into one simulator. Running summary() and coverage() first means a race with a hole in it never silently trains a model.


Chapter Summary

The pipeline

Layer Source Script Key facts (snapshot)
Raw OpenF1 API, Jolpica CSV dump fetch_openf1.py (2.05 s between requests, atomic writes, resumable) JSON per meeting; telemetry gzipped per driver
Processed parquet build_openf1.py, build_jolpica.py 268,783 OpenF1 laps (2023–2026 R21); Jolpica 1950–2026
Analysis toolkit + Box Box f1data, history, telemetry, RaceData 83.3 % of race laps clean

Formulas and checks

Item Definition Value in the snapshot
Clean lap not lap 1; not pit in/out; GREEN all lap; timed; ≤ 107 % of driver's stint median 84,881 of 101,949 race laps
Distance $d_n=\sum \tfrac{v_{i-1}+v_i}{2}\Delta t_i$ median −0.94 % vs official length (19 good laps)
Lap delta $\Delta t(d)=t_\text{cmp}(d)-t_\text{ref}(d)$ on a 5 m grid, laps rescaled to equal length final value = lap-time gap
Green-flag pit loss in-lap + out-lap − 2 × median clean lap nearby Albert Park 20.9 s (raw stints: 15.6 s)
Source agreement OpenF1 vs Jolpica lap times 99.991 % exact from lap 2; lap 1 +0.389 s (median)
Telemetry rate median interval between samples 0.240 s (3.74 Hz mean); ~24 m apart above 300 km/h
Frozen feed all of speed, rpm, throttle, gear unchanged while moving > 2 s on 9.4 % of 2026 fastest qualifying laps

Decision checklist before any analysis

  1. Which source, which seasons, which session kind (R, Q, S, SQ, FP*; testing excluded)?
  2. Did you join on keys (session, driver_ref, date), not names? Did you run the first join as an outer join with an indicator?
  3. Does the coverage check show holes (OpenF1 vs Jolpica lap counts)?
  4. Are you using clean laps, and is "clean" right for this question (deleted laps in qualifying; traffic in pace work)?
  5. For pit work at Monaco, Montreal or Melbourne, are the stint boundaries the fixed ones?
  6. For telemetry: plotted against time first? frozen-run check passed? laps aligned on distance and rescaled? resolution (~24 m at speed) respected?
  7. Have you said which channels you don't have?

What's Next

You now have the data, the cleaning rules and a module that checks a session before you trust it. Chapter 3 puts that data to physical work: we use the speed traces you just learned to align to estimate drag and downforce, and to see what straight-line speed tells us about a car's aerodynamic choices. Chapter 3 starts with the force that defines modern F1 and that no one can see.