Models API Reference
The models module provides an object-oriented interface for working with Formula 1 data. These classes extend pandas DataFrame and Series objects with domain-specific methods for F1 analysis. Filter, analyze, and visualize racing data with few lines of code.Overview
All model classes in tif1 are built on top of pandas data structures. They provide familiar DataFrame and Series interfaces plus specialized methods for F1 data manipulation. This design allows pandas operations alongside tif1-specific functionality.Key Features
- Lazy Loading: Data is loaded on-demand for optimal performance and memory efficiency
- Method Chaining: Fluent API design enables expressive, readable code
- FastF1 Compatibility: Drop-in replacement for FastF1 with minimal code changes
- Type Hints: The classes work as type annotations for IDE autocomplete and type checking
- Automatic Validation: Built-in data validation and error handling
- Both Backends: The models are pandas classes. With
lib="polars", the session returns polars versions (PolarsLaps,PolarsLap,PolarsTelemetry,PolarsSessionResults,PolarsDriverResult,PolarsDriver) with the same methods. Refer to Polars classes
Model Hierarchy
The tif1 models form a logical hierarchy that mirrors the structure of F1 data:Laps(DataFrame) → Collection of lap timing data for multiple laps/driversLap(Series) → Single lap with telemetry access and timing informationDriver(Series) → Driver metadata with access to all their lapsTelemetry(DataFrame) → High-frequency sensor data (speed, throttle, brake, etc.)SessionResults(DataFrame) → Race results and final standingsDriverResult(Series) → Individual driver’s race resultCircuitInfo(Dataclass) → Circuit layout information and track markers
Design Philosophy
The models are designed with the following principles:- Simple Access Patterns: Natural property access (for example,
lap.telemetry,driver.laps) - Consistent Filtering: All filtering methods follow the
pick_*naming convention - Graceful Degradation: Most methods return an empty DataFrame or
Nonewhen data is unavailable.Driver.get_lap()raisesLapNotFoundErrorinstead - Session Context: All models except
CircuitInfokeep a reference to their parent session for direct data access - Performance First: Optimized for speed with vectorized operations and caching
Laps
TheLaps class represents a collection of lap timing data and is the primary interface for filtering and analyzing multiple laps. It inherits from pandas.DataFrame, providing all standard DataFrame operations plus specialized F1-specific filtering methods. This is the most commonly used class in tif1, serving as the entry point for most lap-based analysis.
Class Overview
Inheritance:pandas.DataFrame → Laps
Module: tif1.models (canonical module; re-exported by tif1.core for backward compatibility)
Common Access Patterns
TheLaps class can be accessed through multiple pathways, depending on the analysis needs:
Data Structure
Each row in aLaps DataFrame represents a single lap with complete timing and metadata. The DataFrame contains the following column categories. The dtypes below are for the pandas backend.
On pandas,
LapTime is a timedelta: comparing it to a number such as 90 raises TypeError. Use LapTimeSeconds (float seconds) or pd.Timedelta(seconds=90). On polars, the timing columns are Duration("ns"), LapStartDate is Datetime("ns"), LapNumber is Int64, and Driver, Team, Compound, and TrackStatus are String. The polars frame has no index column.Core Identity Columns
Driver(category): 3-letter driver code (for example, “VER”, “HAM”, “LEC”)DriverNumber(str): Car racing number (for example, “1”, “44”, “16”)Team(category): Full team name (for example, “Red Bull Racing”, “Mercedes”)LapNumber(float): Sequential lap number within the session
Timing Columns (timedelta64[ns])
All timing columns are stored as pandas timedelta objects for precise time arithmetic:LapTime: Total lap time from start line to start lineLapStartTime: Session time when the lap startedTime: Session time when the lap was completedSector1Time,Sector2Time,Sector3Time: Individual sector timesSector1SessionTime,Sector2SessionTime,Sector3SessionTime: Session times at sector completionPitInTime: Session time when entering pit lane (NaT if no pit stop)PitOutTime: Session time when exiting pit lane (NaT if no pit stop)
Speed Trap Columns (float64, km/h)
SpeedI1: Speed at intermediate 1 timing pointSpeedI2: Speed at intermediate 2 timing pointSpeedFL: Speed at finish lineSpeedST: Speed at speed trap location
Tire Information
Compound(category): Tire compound (“SOFT”, “MEDIUM”, “HARD”, “INTERMEDIATE”, “WET”)TyreLife(float): Number of laps completed on this tire setFreshTyre(bool): Whether this is a fresh (unused) tire setStint(float): Stint number within the session
Lap Metadata
TrackStatus(category): Every track status seen during the lap, as one string. The codes are “1”=Green, “2”=Yellow, “4”=Safety Car, “5”=Red Flag, “6”=VSC, and “7”=VSC Ending. For example, “41” contains both 4 and 1.Position(float): Track position at lap completionIsPersonalBest(bool): Whether the lap was the personal best of the driver when it was set.pick_fastest()picks among these laps. Before 2018, the laps come from the Ergast timings. tif1 then sets it on each lap that is faster than every earlier lap of the driverDeleted(nullable boolean): Whether the lap time was deleted by race controlDeletedReason(str): Reason for lap deletion (if applicable)IsAccurate(bool): Whether the lap has accurate timing dataFastF1Generated(bool): Internal flag for data source tracking
Qualifying-Specific
QualifyingSession(str): Which qualifying session (“Q1”, “Q2”, “Q3”). Only qualifying sessions have this column.
Derived Columns
LapTimeSeconds(float): Lap time in seconds (derived from LapTime for convenience)LapStartDate(datetime64): Wall-clock date and time of the lap startms1,ms2,ms3,drv,team: Raw source fields kept for compatibilityindex: A leading integer column.to_csv(index=False)still writes it; drop it first when it is not needed
Weather Data (per-lap)
When weather data is available, each lap includes the columns below. They are misaligned in the source data. In the 2025 Bahrain race, 435 of the 1,128 laps carry a sample other than the one that the fastf1 rule picks. For the sample of a lap, useget_weather_data(), which reads session.weather_data:
WeatherTime(timedelta): Weather observation timeAirTemp(float): Air temperature in °CTrackTemp(float): Track surface temperature in °CHumidity(float): Relative humidity percentagePressure(float): Atmospheric pressure in mbarWindSpeed(float): Wind speed in m/sWindDirection(Int64): Wind direction in degreesRainfall(bool): Whether it is raining
Properties
Reference to the parent Session object. This provides access to session-level data and methods, enabling operations like telemetry loading and driver information lookup. The session reference is automatically propagated when filtering or slicing Laps objects, ensuring that derived objects maintain full context.Usage:
The same data as a plain
pandas.DataFrame (fastf1 parity). Some debuggers and IDEs show a plain frame better than a subclass.Core Filtering Methods
The Laps class provides a complete set of filtering methods that can be chained together for complex queries. All filtering methods return new Laps objects, preserving the original data (immutable operations). These methods are optimized for performance using pandas’ vectorized operations.pick_driver(identifier)
Filter laps to a single driver using flexible identifier matching. This is one of the most commonly used methods in tif1.
identifier: Can be one of several formats for maximum flexibility:str: 3-letter driver code (for example, “VER”, “HAM”, “LEC”) - most common usageint: Driver racing number (for example, 1, 44, 16)dict: Dictionary containing driver info with keys like “driver”, “dn”, “RacingNumber”, “Abbreviation”- Object: Any object with a
driverorAbbreviationattribute
Lapsobject containing only laps from the specified driver. Returns empty Laps if driver not found.
- Case-sensitive for driver codes, as the fastf1
pick_driver():pick_driver("ver")returns no laps.pick_drivers()upper-cases the codes - A number or a string of digits matches
DriverNumber. Any other value must equalDriver - Automatically normalizes various identifier formats to internal representation
- Returns empty Laps if driver not found (no exception raised) - allows graceful handling
- Preserves session reference in returned object for continued data access
- Uses vectorized pandas operations for O(n) performance even with large datasets
- Time Complexity: O(n) where n is the number of laps
- Space Complexity: O(m) where m is the number of matching laps
- Optimized with pandas boolean indexing (no Python loops)
pick_drivers(identifiers)
Filter laps to multiple drivers simultaneously. Useful for comparing performance between specific drivers or analyzing battles.
identifiers: One identifier or any iterable of them. A list, a tuple, a set, a pandas or polars Series, a numpy array, and a generator all work. The formats are those ofpick_driver, and one iterable can mix them.
Lapsobject containing laps from all specified drivers. Returns empty Laps if no matching drivers found.
- Accepts mixed identifier types in the same list (for example,
["VER", 44, {"driver": "LEC"}]) - Upper-cases the driver codes, as fastf1 does, so
"ver"matches"VER" - A number or a string of digits matches
DriverNumberonly - Rows keep their original order in the laps table, not the identifier order
- Duplicate identifiers do not duplicate rows
- Returns empty Laps if no matching drivers found
- Preserves all lap metadata and session context
- Time Complexity: O(n) where n is the number of laps
- More efficient than multiple
pick_drivercalls combined with concatenation - Uses pandas’
isin()method for vectorized filtering
- Comparing performance between specific drivers
- Analyzing battles between teammates or rivals
- Creating visualizations with selected drivers
- Team-level analysis (all drivers from specific teams)
- Qualifying session analysis (top 10 drivers)
pick_fastest(only_by_time=False)
Get the single fastest lap from the collection. This is a convenience method that returns a Lap object (pandas Series) rather than a Laps DataFrame.
only_by_time(bool, default=False): WhenFalse, only the laps withIsPersonalBest == Truecount, as in FastF1. A deleted lap is never a personal best. WhenTrue, the result is the lap with the lowestLapTimeof any lap.
Lapobject representing the fastest lap, orNoneif no valid laps found
- Only considers laps with valid lap times (non-null, non-NaN)
- Takes only the
IsPersonalBestlaps unlessonly_by_time=True. A frame without anIsPersonalBestcolumn skips the deleted laps instead - Returns the lap with the minimum
LapTimevalue - Returns
Noneif the collection is empty or has no valid lap times. With the defaultonly_by_time=False, it also returnsNonewhen no lap is a personal best - In the 2025 Bahrain Grand Prix qualifying, HUL’s lap 13 (1:31.693) is not a personal best.
pick_fastest()returns his lap 5 (1:32.067, his Q1 time), andpick_fastest(only_by_time=True)returns lap 13.session.get_fastest_laps()andDriver.get_fastest_lap()skip only the deleted laps, so they return lap 13 - Preserves session context in the returned Lap object
- If multiple laps have identical fastest times, returns the first occurrence
- Time Complexity: O(n) for finding minimum
- Efficient pandas vectorized operation
pick_quicklaps(threshold=None)
Filter laps within a percentage of the fastest lap time. This is useful for analyzing competitive laps and excluding outliers or slow laps affected by traffic, pit stops, or incidents.
threshold(float | None, default=None): Percentage multiplier for the fastest lap time.Noneuses the class attributeLaps.QUICKLAP_THRESHOLD(1.07, the F1 qualifying 107% rule), as in fastf1. Use a value of 1.0 or more.
Lapsobject containing only laps within the threshold. Returns empty Laps if no laps meet the criteria.
- Calculates the fastest lap time in the collection
- Returns all laps where
LapTime < fastest_time * threshold: strictly below, as in fastf1 - Only considers laps with valid lap times (non-null, non-NaN)
- Returns the laps unchanged if no valid lap times exist
- Preserves session context and all lap metadata
- Time Complexity: O(n) - one pass to find minimum, one pass to filter
- Efficient pandas vectorized operations
- Filtering out slow laps affected by traffic or incidents
- Analyzing competitive pace without outliers
- Implementing F1’s 107% qualifying rule
- Tire degradation analysis with consistent pace
- Race pace analysis excluding pit laps and safety car periods
pick_tyre(compound) / pick_compounds(compounds)
Filter laps by tire compound. Essential for tire strategy analysis and understanding performance characteristics of different compounds.
compound(str): Single tire compound name. Valid values: “SOFT”, “MEDIUM”, “HARD”, “INTERMEDIATE”, “WET”, “UNKNOWN”, “TEST_UNKNOWN”compounds(str | Iterable[str]): One compound name or any iterable of them forpick_compounds
Lapsobject containing only laps on the specified compound(s)
- Compound names are upper-cased, as in fastf1, so
"soft"matches"SOFT" - Returns empty Laps if no laps match the compound
pick_tyreis a convenience wrapper forpick_compoundswith a single compound- Preserves all lap metadata and session context
pick_lap(lap_number) / pick_laps(lap_numbers)
Filter by specific lap number(s). Useful for analyzing specific moments in a race or comparing performance at the same point in different stints.
lap_number(int): Single lap number to filterlaps=: The earlier tif1 keyword forlap_numbers. It still workslap_numbers(the fastf1 name): Can be:int: Single lap number. A whole float such as3.0also workslist[int]: Multiple specific lap numbers, or any other iterable of themslice: Range of laps (for example,slice(10, 20)for laps 10-20 inclusive)
Lapsobject containing only the specified lap(s)
- Lap numbers are 1-indexed (first lap is lap 1)
- Returns empty Laps if lap number does not exist
- A fractional lap number such as
3.5raisesValueError, as in fastf1 pick_lapmatches one lap number;pick_lapsalso accepts other iterables, such asrange(1, 11)- Slice ranges are inclusive on both ends
- Preserves all driver data (returns laps from all drivers at that lap number)
- Analyzing race starts (lap 1)
- Comparing performance at specific race stages
- Identifying key moments (safety car laps, pit stop windows)
- Studying tire warm-up (first few laps of a stint)
- End-of-race analysis (final laps)
pick_team(name) / pick_teams(names)
Filter laps by team name. Useful for team-level analysis and comparing constructor performance.
name(str): Full team name (for example, “Red Bull Racing”, “Mercedes”, “Ferrari”)names(str | Iterable[str]): One team name or any iterable of them forpick_teams
Lapsobject containing only laps from the specified team(s)
- Team names must match exactly (case-sensitive), as in fastf1
- Returns empty Laps if team not found
pick_teamis a convenience wrapper forpick_teamswith a single team- Includes all drivers from the specified team(s)
pick_track_status(status, how="equals")
Filter by track status (green flag, yellow flag, safety car, etc.). Essential for analyzing race conditions and their impact on lap times.
status(str): Track status code:- “1” = Green flag (normal racing)
- “2” = Yellow flag
- “4” = Safety Car
- “5” = Red Flag
- “6” = Virtual Safety Car (VSC)
- “7” = VSC Ending
how(str): Matching mode, as in fastf1:- “equals” (default): The lap code is
status - “contains”: The lap code contains
status - “excludes”: The lap code does not contain
status - “any”: The lap code contains at least one character of
status - “none”: The lap code contains no character of
status
- “equals” (default): The lap code is
Lapsobject containing only laps with the specified track status
ValueError: Any otherhowvalue
TrackStatus code string of each lap. It does not read the time-based session.track_status table. With the codes "4" and "41", pick_track_status("41", how="any") keeps both laps, and how="none" keeps neither.
Example Usage:
pick_wo_box() / pick_box_laps(which="both")
Filter laps by pit stop activity. Critical for race strategy analysis and understanding pit stop impact.
which(str): Forpick_box_laps:- “both” (default): Laps with either pit in or pit out
- “in”: Only laps where driver entered pits
- “out”: Only laps where driver exited pits
Lapsobject filtered by pit activity
pick_wo_box()returns laps without any pit activity (neither PitInTime nor PitOutTime)pick_box_laps()returns laps with pit activity- Useful for excluding slow pit laps from pace analysis
- Returns the laps unchanged if the
PitInTimeorPitOutTimecolumn does not exist
pick_not_deleted() / pick_accurate()
Filter for valid and accurate laps. Essential for ensuring data quality in analysis.
pick_not_deleted(): Laps that were not deleted by race controlpick_accurate(): Laps with accurate timing data
pick_not_deleted()filters out laps whereDeleted == Truepick_accurate()filters for laps whereIsAccurate == True- Often used together for high-quality data analysis
- Returns all laps if the respective column does not exist
Telemetry Access Methods
get_telemetry() / telemetry property
Access high-frequency telemetry data for the laps in the collection. This feature enables detailed analysis of driver inputs and car behavior.
frequency:Noneuses theTELEMETRY_FREQUENCYclass attribute of the backend’s telemetry class (Telemetryon pandas,PolarsTelemetryon polars),"original"by default."original"keeps the published samples. A number resamples the merged frame to that rate in Hz withresample_channels(), as fastf1 does. Any other value raisesValueError
TelemetryDataFrame with high-frequency sensor data
- Single-driver requirement: Only works when all laps are from the same driver
- Raises
ValueErrorif laps contain multiple drivers get_telemetry()includes driver-ahead channels (DriverAhead, DistanceToDriverAhead)get_telemetry(frequency=10)returns one sample every 100 ms- The
telemetryproperty returns the same channels: tif1 telemetry already carries both driver-ahead columns - Returns empty Telemetry if no data available
- The telemetry of several laps is one slice, as in fastf1.
Timeruns from the start of the first lap (SessionTimeminus theLapStartTimeof that lap) and does not restart at each lap. The laps are in session order, and the sample that two consecutive laps share at their boundary appears once Distancerestarts at each lap.add_distance()integrates it again over the whole frame- A single lap is not changed: its
Timestarts at 0 - Preserves session context for continued analysis
- Lazy-loaded on first access
- Cached for subsequent accesses
- May trigger network requests if not cached
- Detailed lap analysis (speed traces, braking points, throttle application)
- Driver comparison (racing lines, braking techniques)
- Car setup analysis (gear ratios, DRS effectiveness)
- Overtaking analysis (with driver-ahead data)
- Track mapping (X, Y, Z coordinates)
get_car_data() / get_pos_data()
FastF1 compatibility aliases for telemetry access. These methods provide the same functionality as telemetry property but with FastF1-compatible naming.
pad,pad_side,interpolate_edges: As inTelemetry.slice_by_lap(). Withpad, tif1 slices the session-long telemetry of the driver (session.car_data[driver]), so the padding samples come from the neighbouring laps. Other keywords are ignored
TelemetryDataFrame (same astelemetryproperty)
get_car_data()returns full telemetry dataget_pos_data()returns position data (same as car data in tif1)- The laps of one driver give one multi-lap slice, as
get_telemetry()does - For multi-driver laps, concatenates telemetry from all laps.
padneeds single-driver laps - With
pad, the result has a fresh index from 0 to n-1, as in fastf1
get_weather_data()
Get the weather sample of each lap, as in fastf1.
DataFramewith one row per lap. The columns areTime(the session time of the sample),AirTemp,Humidity,Pressure,Rainfall,TrackTemp,WindDirection, andWindSpeed, with the dtypes ofsession.weather_data
- The samples come from
session.weather_data, with the fastf1 rule. A lap takes the first sample within[LapStartTime, Time], else the last sample before the end of the lap - A lap without a sample gets a row of missing values
- The first call loads
weather.jsonif the session has not loaded it - The
WeatherTimeand weather columns of the laps table are misaligned in the source data. In the 2025 Bahrain race, 435 of the 1,128 laps carry a sample other than the one that the fastf1 rule picks. These columns are used only when the session has no weather table - The rows keep the index of the laps. fastf1 indexes them by the weather samples instead
- On a polars session, the result is a plain
polars.DataFrame
Iteration Methods
iterlaps(require=None)
Iterate over laps with optional required columns. This is the recommended way to process each lap individually.
require(list[str] | None): List of column names that must have non-null values. Laps with null values in these columns are skipped. The default (None) and an empty list yield every lap, as in fastf1.
_IterLapResult: Tuple-like object with:index: DataFrame index of the laplap: Lap object (pandas Series) with lap data
- Skips laps with null values in required columns
- Each yielded lap holds every column, the null ones included, as the fastf1 rows do
- Preserves session context in yielded Lap objects
- A required column that does not exist yields no laps, as in fastf1
- Processing each lap individually
- Calculating custom statistics
- Filtering with complex logic
- Accessing telemetry for each lap
- Building custom data structures
Qualifying-Specific Methods
split_qualifying_sessions()
Split qualifying laps into Q1, Q2, and Q3 sessions, as in fastf1.
list[Laps | None]: [Q1 laps, Q2 laps, Q3 laps]. A segment without laps isNone
- The algorithm is the fastf1 one
- The
QualifyingSessioncolumn (“Q1”, “Q2”, “Q3”) decides when the laps have it - Without that column,
session.session_statussplits the laps by time. EachStartedrow opens a segment, but a restart after anAbortedrow (a red flag) continues the segment. AFinishedrow also ends the suspension - A lap goes to the segment of its
LapStartTime. An out-lap that starts before a split and ends after it goes to the next segment - Without a session status, the two longest gaps of more than 5 minutes between lap start times split the laps
- A session that is not Qualifying, Sprint Qualifying, or Sprint Shootout raises
ValueError("Session is not a qualifying session!"), as in fastf1 - Each returned Laps object preserves session context
- The pandas and polars classes return the same segments
DataFrame Operations
TheLaps class inherits all pandas DataFrame operations, so standard pandas methods work:
Lap
TheLap class represents a single lap with timing data and access to high-frequency telemetry. It inherits from pandas.Series. The result is a row-like object with named fields, accessed like a dictionary or via attribute access.
Class Overview
Inheritance:pandas.Series → Lap
Module: tif1.models (canonical module; re-exported by tif1.core for backward compatibility)
Common Access Patterns:
Data Structure
ALap object is a pandas Series containing all the lap data columns described in the Laps section. Access any column value with dictionary-style or attribute-style access:
Properties
The value of the Note: Returns
LapNumber column. On pandas, this value is a float, for example 19.0. Convert it with int() before passing it to Driver.get_lap().Usage:None if the LapNumber column is missing.The 3-letter driver code extracted from the Note: Returns
Driver column. This identifies which driver completed this lap.Usage:None if the Driver column is missing.High-frequency telemetry data for this lap. This property provides lazy-loaded access to detailed sensor data including speed, throttle, brake, gear, DRS, and position information.Behavior:Error Handling:
- Loaded lazily on first access (not fetched until this property is accessed)
- Cached after first load for performance
- Returns empty Telemetry DataFrame if data not found or unavailable
- Automatically handles network requests and caching
- Preserves session context for continued analysis
- First access may trigger a network request
- Subsequent accesses are instant (cached in memory)
- A lap has several hundred samples: lap 19 of VER in the 2024 Monaco race has 591
Reference to the parent Session object. This maintains the connection to the session that created this lap, enabling access to session-level data and methods.Usage:
Methods
get_telemetry()
Load telemetry data with driver-ahead channels (FastF1 naming). In tif1, the telemetry property already includes these channels, so both return the same columns.
frequency:Noneuses theTELEMETRY_FREQUENCYclass attribute of the backend’s telemetry class (TelemetryorPolarsTelemetry),"original"by default."original"keeps the published samples. A number resamples to that rate in Hz (frequency=10gives one sample every 100 ms)
TelemetryDataFrame with all telemetry channels including:- Clock channels: Date, SessionTime, Time
- Standard channels: Speed, RPM, nGear, Throttle, Brake, DRS, Distance, X, Y, Z
- Driver-ahead channels: DriverAhead, DistanceToDriverAhead
- Includes
DriverAheadandDistanceToDriverAheadcolumns (if available) - Useful for analyzing overtaking opportunities and battles
- Same lazy-loading and caching behavior as
telemetryproperty - Returns empty Telemetry if data not available
- Overtaking analysis
- Battle analysis between drivers
- Gap analysis during racing
- Understanding traffic impact on lap times
get_car_data(**kwargs) / get_pos_data(**kwargs)
FastF1 compatibility aliases for telemetry access. These methods provide the same functionality as the telemetry property but with FastF1-compatible naming conventions.
pad,pad_side,interpolate_edges: As inTelemetry.slice_by_lap(). Withpad, tif1 slices the session-long telemetry of the driver (session.car_data[driver]), so the padding samples come from the neighbouring laps. Other keywords are ignored
TelemetryDataFrame with telemetry data
get_car_data()returns full telemetry data (same astelemetryproperty)get_pos_data()returns position data (in tif1, same as car data)- Both methods are provided for FastF1 compatibility
- No functional difference between the two in tif1
lap.get_car_data(pad=2)adds two samples of the neighbouring laps on each side
get_weather_data()
Get the weather sample of this lap, as in fastf1.
Seriesnamed after the lap:Time(the session time of the sample),AirTemp,Humidity,Pressure,Rainfall,TrackTemp,WindDirection, andWindSpeed.PolarsLap.get_weather_data()returns adictwith the same keys
- The sample comes from
session.weather_data, with the fastf1 rule: the first sample within[LapStartTime, Time]of the lap, else the last one before the lap ended - The weather columns of the lap row (
WeatherTime,AirTemp, …) are misaligned in the source data. They are used only when the session has no weather table, so they can differ from the result - A lap without a weather sample gives a Series of NaN with the same keys, as in fastf1. On polars, the dict holds
Nonevalues
Common Usage Patterns
Analyzing a Single Lap
Comparing Two Laps
Finding Personal Best Lap
Driver
TheDriver class represents a driver’s participation in a session. It provides access to the driver’s result, laps, and analysis methods. It inherits from DriverResult (a pandas.Series): the values are the results row of the driver, as the fastf1 get_driver() returns.
Class Overview
Inheritance:pandas.Series → DriverResult → Driver
On a polars session, session.get_driver() returns a PolarsDriver with the same values and methods. Refer to Polars classes.
Module: tif1.models (canonical module; re-exported by tif1.core for backward compatibility)
Common Access Patterns:
session.drivers holds driver numbers as strings (“81”, “63”, …), not codes. session.drivers_df["Driver"] holds the 3-letter codes in the same order.
Data Structure
ADriver object is a pandas Series that holds the results row of the driver: the 22 fastf1 result columns first, then the tif1 extras. The data is stored in the Series itself and can be accessed using dictionary-style or attribute-style access:
Available Fields (in Series data):
DriverNumber(str): Racing number (for example, “1”, “44”, “16”)Abbreviation(str): 3-letter driver code (for example, “VER”, “HAM”, “LEC”)TeamName(str): Full team name (for example, “Red Bull Racing”, “Mercedes”)TeamColor(str): Team color hex code without#(for example, “3671C6”)FirstName(str): Driver’s first name (for example, “Max”, “Lewis”)LastName(str): Driver’s last name (for example, “Verstappen”, “Hamilton”)FullName(str): Driver’s full name (for example, “Max Verstappen”)HeadshotUrl(str): URL to driver headshot imagePosition,ClassifiedPosition,GridPosition,Status,Points,Laps,Time,Q1,Q2,Q3: The classification, as insession.results- The other
session.resultscolumns:BroadcastName,DriverId,TeamId,CountryCode, and the tif1 extras (TimeGap,FastestLapRank,PermanentNumber, …)
Position and ClassifiedPosition are by best lap, Status is "Finished", Laps counts the laps, and Time is the best lap that is not deleted. GridPosition and Points are NaN, and DriverId and TeamId come from the Ergast race results. get_driver() returns the same row whether results was read first or not.
get_driver() accepts the abbreviation, the car number, the full name, or the number/Abbreviation label of a shared car. For a car that two drivers shared, the car number gives the first driver of the car and the label gives the other one. The pandas Driver is named after its results label: .name is "1", or "8/fagioli" for the second driver of car 8 in the 1951 French Grand Prix.
Access Examples:
Properties
The 3-letter driver code (for example, “VER”, “HAM”, “LEC”). This is stored as an attribute (not in the Series data) and provides quick access to the driver identifier.Usage:Note: This is the primary identifier for the driver and is used throughout tif1 for filtering and lookups.
From
DriverResult: True when Status is not "Finished", "Lapped", or "+N Lap(s)". An empty status gives False.Reference to the parent Session object. This maintains the connection to the session, enabling access to session-level data and methods.Usage:
All laps completed by this driver in the session. This property provides lazy-loaded access to the driver’s lap data.Type: Returns Common Patterns:
Laps (pandas backend) or PolarsLaps (polars backend)Behavior:- Loaded lazily on first access (not fetched until this property is accessed)
- Cached after first load for performance
- Returns empty DataFrame if no laps found
- Automatically filters session laps to this driver
- Preserves session context in returned Laps object
- First access may trigger a network request if not cached
- Subsequent accesses are instant (cached in memory)
- Efficient filtering using pandas/polars vectorized operations
Methods
get_lap(lap_number)
Get a specific lap by number. This is the primary method for accessing individual laps from a driver.
lap_number(int): The lap number to retrieve. Must be a positiveint. Convert aLapNumbervalue such as19.0withint()first.
Lapobject for the specified lap
LapNotFoundError: If the lap does not exist for this driverValueError: Iflap_numberis zero or negativeTypeError: Iflap_numberis not anint(for example, the float19.0)
- Uses optimized O(1) lookup with internal lap index map
- Validates lap number before lookup
- Returns a Lap object with full lap data and telemetry access
- Preserves session context in returned Lap object
- Raises specific exceptions for better error handling
- Time Complexity: O(1) after first call (builds index map on first access)
- Space Complexity: O(n) for index map where n is number of laps
- Subsequent calls are fast (dictionary lookup)
- Analyzing specific race moments (lap 1, pit stop laps, final lap)
- Comparing performance at different race stages
- Telemetry analysis for specific laps
- Incident investigation
- Tire warm-up analysis (first lap of stint)
get_fastest_lap()
Get this driver’s fastest lap as a single-row DataFrame. This is a convenience method for quickly accessing the driver’s best performance.
DataFrame: Single-row DataFrame containing the fastest lap data. Returns empty DataFrame if no valid laps found.
- Filters to laps with valid lap times (non-null, non-NaN)
- Skips deleted laps (
Deleted == True) - Returns the lap with minimum
LapTimevalue - Returns empty DataFrame (not None) if no valid laps exist, for example when every timed lap was deleted
- Result is a single-row DataFrame (a
Lapson pandas), not aLapobject - Includes all lap columns
- Time Complexity: O(n) where n is number of driver’s laps
- Efficient pandas vectorized operation
- May use cached lap data if already loaded
get_fastest_lap_tel()
Get telemetry from this driver’s fastest lap. This is a convenience method that combines finding the fastest lap and loading its telemetry in one call.
DataFrame: Telemetry DataFrame for the fastest lap. Returns empty DataFrame if not found.
- Automatically identifies the fastest lap
- Loads telemetry for that lap
- Returns empty DataFrame if no fastest lap or no telemetry available
- More efficient than calling
get_fastest_lap()then loading telemetry separately - Uses internal optimization to avoid redundant lookups
- Optimized to minimize data fetching
- May use cached telemetry if available
- Single method call for convenience
- Quick access to best performance telemetry
- Driver comparison visualizations
- Optimal racing line analysis
- Braking point identification
- Gear shift analysis
- DRS effectiveness study
Common Usage Patterns
Complete Driver Analysis
Comparing Drivers
Telemetry
TheTelemetry class represents high-frequency data recorded throughout a lap or multiple laps. It inherits from pandas.DataFrame with additional slicing and analysis methods specifically designed for telemetry data. This class enables detailed analysis of driver inputs, car behavior, and racing lines.
Class Overview
Inheritance:pandas.DataFrame → Telemetry
Module: tif1.models (canonical module; re-exported by tif1.core for backward compatibility)
Sampling Rate: About 7-8 samples per second. A 97.5-second lap of the 2025 Bahrain race has 740 samples.
Common Access Patterns:
Properties
Reference to the parent Session object. Maintains connection to the session for accessing session-level data.
Driver code for this telemetry data (for example, “VER”, “HAM”). The telemetry of one lap sets it. Telemetry built from several laps can have
None; read the Driver column then.Class attribute with the default sampling policy of
get_telemetry() and merge_channels(): "original". Set it to a rate in Hz to resample by default, as in fastf1.Constructor and Channels
drop_unknown_channels=True: Keep only the registered channels and theDriverandLapNumbercolumns. Other columns are droppedregister_new_channel(): Register a custom column as a"continuous","discrete", or"excluded"channel, with the fastf1 arguments and checks.resample_channels()then averages a continuous channel and holds a discrete one.fill_missing()and the resampling leave an excluded channel alone. A continuous channel needs aninterpolation_method, and an unknownsignal_typeraisesValueError. The method is stored under the"method"key, as in fastf1. tif1 interpolates every continuous channel linearly. fastf1 uses a quadratic spline forX,Y,Z, andDistance(seeslice_by_time)
Available Columns
Telemetry DataFrames contain high-frequency sensor data. The columns follow the fastf1 order:Date, SessionTime, DriverAhead, DistanceToDriverAhead, Time, RPM, Speed, nGear, Throttle, Brake, DRS, Source, Distance, RelativeDistance, Status, X, Y, Z. The tif1 extras AccelerationX, AccelerationY, AccelerationZ, Driver, and LapNumber come last.
Clock and Source
Time and Distance
Speed and Engine
Driver Inputs
Position (3D Coordinates)
Acceleration
Lap Context
Driver-Ahead Data (when available)
Note: Not all columns are always present. Use
if "ColumnName" in tel.columns to check availability.
Core Methods
slice_by_time(start_time, end_time, pad=0, pad_side="both", interpolate_edges=False)
Slice telemetry by time window. Essential for analyzing specific sections of a lap or comparing the same time window across different laps.
start_time: Start time (timedelta, float seconds, or int seconds). The time is a session time: tif1 telemetry has aSessionTimecolumn, so the slice reads it, as fastf1 does. Only a frame withoutSessionTimeuses the lap-relativeTimeend_time: End time (same format as start_time)pad(int, default=0): Number of samples to include before/after the slicepad_side(str, default=“both”): Where to apply padding (“both”, “before”, “after”)interpolate_edges(bool, default=False): Add one interpolated sample at each edge of the slice, as fastf1 does. A continuous channel takes the linear value between the two neighbouring samples, and a discrete channel takes the value in force. The added samples have theSource"interpolation". Nothing is added at an edge that falls on a sample. fastf1 fits a quadratic spline throughX,Y,Z, andDistanceinstead. On real data the two methods differ by about 0.1 m inX/Yand about 1 cm inDistance. Both values are below the noise of the position data. A lap’s start and end are stored samples, so lap edges get no interpolated sample with either method
TelemetryDataFrame containing only the specified time window
- Time values can be provided as timedelta, float (seconds), or int (seconds)
- Automatically adjusts Time column to be zero-based relative to start_time
- Padding adds extra samples for context
- Returns empty Telemetry if time window does not exist
slice_by_lap(ref_laps, pad=0, pad_side="both", interpolate_edges=False)
Slice telemetry by lap reference. Useful for extracting telemetry for specific laps from a larger telemetry dataset.
ref_laps: Lap or Laps object to use as referencepad(int, default=0): Number of samples to include before/afterpad_side(str, default=“both”): Where to apply paddinginterpolate_edges(bool, default=False): Add one interpolated sample at each edge, as inslice_by_time()
TelemetryDataFrame for the specified lap(s)
- tif1 telemetry has a
SessionTimecolumn, so the slice uses the lap start and end times (LapStartTimeandTimeof the laps), as in fastf1 - A frame without
SessionTimeis sliced on theLapNumberandDrivercolumns instead session.car_data[driver].slice_by_lap(lap, pad=2)takes the padding samples from the neighbouring laps- Raises ValueError if ref_laps contains multiple drivers
- Returns empty Telemetry if lap not found
slice_by_mask(mask, pad=0, pad_side="both")
Slice telemetry using a boolean mask. Useful for custom filtering based on any condition.
mask: Boolean array/Series matching telemetry lengthpad(int, default=0): Number of samples to include before/afterpad_side(str, default=“both”): Where to apply padding
TelemetryDataFrame containing only masked samples
ValueError: If mask length does not match telemetry length
Distance and Position Methods
add_distance() / integrate_distance()
Calculate distance from speed and time. Essential when Distance column is missing.
add_distance(): Telemetry with Distance column addedintegrate_distance(): Series with calculated distances
- Integrates speed over time to calculate distance, from 0 at the first sample of the frame
- Converts speed from km/h to m/s internally
drop_existing=True(the default) integratesDistanceagain over the whole frame and replaces the column, as fastf1 does. TheDistancethat tif1 telemetry carries restarts at each lap, so calladd_distance()on the telemetry of several laps to get one continuous distancedrop_existing=Falsereturns the frame unchanged when it has aDistancecolumn- As in fastf1, the error of the integration grows with the length of the frame. Integrate a few laps at a time
integrate_distance()returns Series without modifying telemetry
add_relative_distance()
Add normalized distance column (0-1 scale). Useful for comparing laps of different lengths.
Telemetrywith RelativeDistance column (0 = start, 1 = finish)
- Divides
Distanceby its last value, as fastf1 does. A frame withoutDistanceuses the integrated speed instead and does not get aDistancecolumn - On the telemetry of several laps, call
add_distance()first: theDistancethat tif1 telemetry carries restarts at each lap drop_existing=Falsereturns the frame unchanged when it has aRelativeDistancecolumn
add_differential_distance(drop_existing=True) / calculate_differential_distance()
Add the distance driven between two samples, as fastf1 does.
drop_existing=Truecomputes theDifferentialDistancecolumn againdrop_existing=Falsereturns the frame unchanged when the column already existscalculate_differential_distance()returns the values without changing the frame
Driver-Ahead Methods
add_driver_ahead() / calculate_driver_ahead()
Add driver-ahead information for analyzing battles and overtaking.
add_driver_ahead(): Telemetry with DriverAhead and DistanceToDriverAhead columnscalculate_driver_ahead(): Tuple of (driver_ahead_array, distance_array) or (driver_ahead, distance, reference_tel)
- tif1 does not calculate the driver ahead itself. It reads the
DriverAheadandDistanceToDriverAheadchannels of the source telemetry. lap.get_telemetry()andlaps.get_telemetry()already include both channels- If the channels are missing,
add_driver_ahead()adds them with missing values (Noneand NaN) - Existing channels are kept for any
drop_existingvalue, because one driver’s telemetry cannot recompute them DriverAheadholds driver numbers as strings (for example, “81”), not 3-letter codes
Track Status Method
add_track_status(drop_existing=True)
Add a TrackStatus column: the status of session.track_status at each sample, with the fastf1 algorithm.
- Each sample takes the status of the last
session.track_statusrow at or before itsSessionTime. A frame withoutSessionTimeusesTime - Without a session or a track status table, every sample is
"1". On polars,df.f1.add_track_status()on a plain frame without a session raisesValueError: passsession= drop_existing=Falsereturns the frame unchanged whenTrackStatusalready exists
Data Processing Methods
fill_missing()
Fill the missing values of the telemetry, the way fastf1 does. Useful for cleaning telemetry data.
Telemetrywith the gaps filled
- Continuous channels (
Speed,RPM,Throttle,X, …) and other float columns are interpolated linearly, in both directions - Discrete channels (
nGear,DRS,Brake,Status,DriverAhead) take the value in force: a forward fill, then a backward fill.Driver,LapNumber, and other integer or boolean columns are filled the same way. They keep their dtype:nGearstaysInt64and never takes a value such as 2.5 - A missing
Sourcebecomes"interpolation" - The clock columns and the channels registered as
"excluded"are not changed - Only the columns with gaps are changed
merge_channels(other, frequency=None)
Merge telemetry from another source using time-based alignment.
other: Another Telemetry or DataFrame to mergefrequency: Resample the merged frame to this rate in Hz withresample_channels()."original"keeps the merged samples.NoneusesTELEMETRY_FREQUENCYof the backend’s class (TelemetryorPolarsTelemetry),"original"by default
Telemetrywith merged channels
- Matches the samples on the session clock:
Datewhen both frames have it, elseSessionTime, elseTime. It never matches on the lap-relativeTimeof two frames that have a session clock - Every row of this frame is kept and takes the sample of
otherthat is nearest in time. On a tie, it takes the earlier sample - The rows come back in clock order, with a fresh index. A row without a clock is kept, with missing values for the columns of
other, on both backends - A column that both frames have keeps the values of this frame. The copy from
othergets the suffix_other
resample_channels(rule=None, new_date_ref=None, **kwargs)
Resample telemetry to a different frequency, or onto given timestamps. Useful for reducing data size or standardizing sampling rates.
rule(str | None): pandas offset alias for the resampling frequency (for example, “1s” = 1 second, “100ms” = 100 milliseconds). Legacy upper-case aliases such as “1S” are translated. When neither argument is given, tif1 uses"1s".new_date_ref(Series | None): Timestamps to resample onto, matched against theDatecolumn. A frame withoutDateraisesValueError.**kwargs: Accepted for compatibility and ignored
rule and new_date_ref. Both together raise ValueError.
Returns:
Telemetryresampled to specified frequency, with the same columns in the same order
rule:
- The bins start at the first sample on the session clock (
Date, elseSessionTime, elseTime), as fastf1’smerge_channels(frequency=...)does - Continuous channels (
Speed,RPM,X, …) are the mean of each bin, interpolated across empty bins - Discrete channels (
nGear,DRS,Brake,DriverAhead,Source,Status,LapNumber) and text columns take the value in force at the start of each bin DateandSessionTimeadvance with the bins, andTimestarts again at zero
new_date_ref:
- The output has one row for each unique timestamp, sorted
- Continuous channels and the clock columns are interpolated at each timestamp. Before the first sample and after the last sample, they keep the edge value
- The other columns take the value in force at each timestamp
Common Usage Patterns
Basic Telemetry Analysis
Comparing Two Laps
Finding Braking Points
SessionResults
TheSessionResults class contains the classification of a session, one row per driver in classification order, indexed by driver number. A shared car’s later drivers are labelled number/Abbreviation, so the index stays unique. It inherits from pandas.DataFrame. Race, Sprint and Qualifying sessions carry the official Ergast classification merged into the driver list. The other sessions (and every session with ergast=False) are classified from the lap data, as fastf1 does:
- Practice:
Positionby best lap,Status"Finished",Laps, andTime(the best lap that is not deleted) - Sprint Qualifying, Sprint Shootout, and Qualifying with
ergast=False: the best accurate lap of each segment fillsQ1toQ3. The order is byQ3, thenQ2, thenQ1. A Q1 time outside 107% hasClassifiedPosition"N". A driver out in Q1 or Q2 keeps no time from a later segment (the knockout) - Races and sprints with
ergast=False: laps completed, then the position on the last lap
Class Overview
Inheritance:pandas.DataFrame → SessionResults
Module: tif1.models (canonical module; re-exported by tif1.core for backward compatibility)
Common Access Patterns:
session.results is a PolarsSessionResults frame with the same columns. Refer to Polars classes.
Properties
Reference to the parent Session object. Maintains connection to the session for accessing session-level data.
The same data as a plain
pandas.DataFrame (fastf1 parity). Some debuggers and IDEs show a plain frame better than a subclass.Available Columns
The SessionResults DataFrame contains the following columns:
Note: There is no
Driver or Team column. Use Abbreviation and TeamName. fastf1’s 22 columns come first, in fastf1’s order; the tif1 extras follow. Every column exists in every session; values a session cannot have are NaN, NaT or empty strings.
Usage Examples
Basic Results Access
Analyzing Results
DriverResult
TheDriverResult class represents the result of one driver. It inherits from pandas.Series, so it is a single row of the SessionResults DataFrame. Driver, the class that session.get_driver() returns, is a DriverResult subclass with the same values and dnf property.
Class Overview
Inheritance:pandas.Series → DriverResult
Module: tif1.models (canonical module; re-exported by tif1.core for backward compatibility)
Common Access Patterns:
Properties
Points scored, from the Ergast classification. NaN for practice, qualifying, the sprint qualifying formats, and for
ergast=False. Access via driver_result['Points'].Finish status (in the Series data), for example “Finished” or “+2 Laps”. Access via
driver_result['Status'].Whether the driver did not finish (computed property).Behavior:
- Returns
Falsefor “Finished”, “Lapped” and any “+N Lap(s)” status (a classified finisher, however many laps down) - Returns
Truefor every other status: “Retired”, “Accident”, “Disqualified”, “Did not start”, “Not classified”, … - Returns
FalsewhenStatusis missing or empty - Case-insensitive comparison
Usage Examples
CircuitInfo
TheCircuitInfo class holds information about the circuit layout, including corner locations and track markers. This is a dataclass (not a pandas object) that provides circuit-specific data. It has the attributes of fastf1’s mvapi.CircuitInfo (corners, marshal_lights, marshal_sectors, rotation) and the tif1 extras. tif1.mvapi.CircuitInfo is the same class.
session.get_circuit_info() reads the corners.json file of the session. When the file is missing or uses the old schema (2021 to 2024 seasons), tif1 asks the MultiViewer API. MultiViewer fills the marshal data, the corner letters, and the empty extras. Refer to MultiViewer API. On a polars session, every frame is a polars frame.
Class Overview
Type: Dataclass Module:tif1.models (canonical module; re-exported by tif1.core for backward compatibility)
Common Access Patterns:
Properties
Location of corners on the circuit. DataFrame with columns:
X, Y, Number, Letter, Angle, Distance.Columns:X(float): X coordinate of cornerY(float): Y coordinate of cornerNumber(int): Corner numberLetter(str): Corner letter designation (for example, “a” for a turn 9a). An empty string when the corner has no letterAngle(float): Corner angle in degreesDistance(float): Distance along the lap. The source data usually fills it, andadd_marker_distance()recomputes it from a reference lap
Location of marshal lights, with the same columns as
corners. The new-schema corners.json carries them. For older seasons, the MultiViewer API fills them. The frame is empty only when neither source answers.Location of marshal sectors, with the same columns as
corners. The sources are the same as for marshal_lights.tif1 Extras
When the source does not carry an extra, the extra keeps an empty default (None, "", {}, [], or an empty frame). Attribute access never raises.
Methods
add_marker_distance(reference_lap)
Compute the Distance value for each track marker using telemetry from a reference lap. This method populates the Distance column in the corners DataFrame.
reference_lap(Lap): A Lap object whose telemetry containsX,Y, andDistancecolumns
- Uses best-fit approach to match marker positions with telemetry samples
- For each marker, finds the telemetry sample with minimum squared XY error
- Assigns that sample’s Distance value to the marker
- Modifies the
corners,marshal_lights, andmarshal_sectorsDataFrames in place - Logs warnings if telemetry is unavailable or missing required columns
- Requires valid X, Y, and Distance data in the reference lap’s telemetry
- Loads telemetry from reference lap
- Filters to samples with valid X, Y, Distance values
- For each marker, calculates squared Euclidean distance to all telemetry samples
- Assigns the Distance from the closest telemetry sample
- Mapping corner locations to lap distance
- Analyzing speed through specific corners
- Comparing corner performance between drivers
- Visualizing racing lines with corner markers
- Sector analysis based on corner positions
Complete Usage Examples
Example 1: Complete Race Analysis
Example 2: Telemetry Comparison Visualization
Example 3: Tire Degradation Analysis
LazyTelemetryDict
session.car_data and session.pos_data return it (the same object), as fastf1 does. It can also be constructed with a session (any TelemetryProvider).
- The keys are driver numbers (
"1","81"), as in fastf1. tif1 resolves the car numbers first, so a session whosedrivers.jsonhas no numbers (the 2024 Belgian Grand Prix) still has number keys. The later drivers of a shared car havenumber/Abbreviationkeys, as inresults. A driver code ("VER") or a shared-car label ("2/MOS") also works as a key. - Indexing loads the telemetry of all laps of that driver as one frame, in session order, with each lap-boundary sample once. The first access loads it. Later accesses reuse it.
Timeis the session clock, as in fastf1: it equalsSessionTime.len(), iteration,keys(), andinuse the driver list of the session. They fetch no telemetry.values()anditems()load every driver.- On a polars session, the values are
PolarsTelemetryframes.
TelemetryProvider
year, gp, session, enable_cache, lib, laps, weather_data, and get_fastest_laps_tels; the rest are private session helpers. tif1.core.Session satisfies the protocol structurally as the production adapter; tests can provide lightweight in-memory implementations instead. Decorated with typing.runtime_checkable so structural conformance can be asserted with isinstance.
Polars Classes
On alib="polars" session, tif1 returns polars versions of the models, with the same fastf1 methods. They live in tif1.models_polars, which never imports pandas. tif1 exports them at the top level.
session.laps, driver.laps, get_fastest_laps(), the telemetry of laps, the car_data values, results, and get_driver() return these classes. track_status, session_status, drivers_df, and laps.get_weather_data() return plain polars frames.
Data types: The time columns are Duration("ns"), and LapStartDate and the telemetry Date are Datetime("ns"). Brake is Boolean. PolarsSessionResults uses the fastf1 types: Duration for Q1 to Q3, Time, and TimeGap, Float64 for Position, GridPosition, Points, and Laps, and String for the text columns.
Frame classes:
- The fastf1 methods return the tif1 classes, so a fastf1 chain keeps its methods:
laps.pick_driver("VER").pick_fastest().get_telemetry().- On
PolarsLaps, thepick_*filters return aPolarsLaps,pick_fastest()returns aPolarsLap(orNone),split_qualifying_sessions()returnsPolarsLapssegments (orNone), andtelemetry,get_telemetry(),get_car_data(), andget_pos_data()return aPolarsTelemetry.get_weather_data()returns a plainpolars.DataFrame. - On
PolarsTelemetry, theslice_by_*,add_*,fill_missing(),merge_channels(), andresample_channels()methods return aPolarsTelemetry. PolarsSessionResults.row_for()returns aPolarsDriverResult.
- On
head(),tail(),limit(),slice(),clone(),reverse(), and row selection with[]keep the class and thesessionattribute (anddriveron telemetry).base_class_viewis a property that returns the data as a plainpolars.DataFrame.PolarsSessionResultshas no index:DriverNumberis a column.results.row_for(identifier)(aliasget_driver()) returns thePolarsDriverResultof a car number, an abbreviation, a full name, or a shared-car label. No match, or an empty string, raisesDriverNotFoundError.
PolarsLap,PolarsDriverResult, andPolarsDriverread their row once.lap["LapTime"],lap.LapTime, andlap.get("LapTime")return Python scalars..frameis the one-row frame and.to_dict()returns the row as a dict. OnPolarsLap,.nameis the row position in the source frame. OnPolarsDriverResultandPolarsDriver,.nameis the label of the row in the pandasresultsindex, as in fastf1. Examples are"1", and"8/fagioli"for a shared car.PolarsLaps.iterlaps()yields(index, PolarsLap)pairs.PolarsLap.get_weather_data()returns a dict.PolarsDriverResult.dnffollows the pandas rule.PolarsDriveraddslaps,fastest_lap,telemetry,get_telemetry(frequency=),get_lap(),get_fastest_lap(), andget_fastest_lap_tel().
The df.f1 namespace
A native polars operation such as filter(), select(), sort(), or with_columns() returns a plain polars.DataFrame, not the tif1 class. tif1 registers a polars DataFrame namespace, f1, so that df.f1.pick_fastest() keeps the tif1 methods on any frame.
df.f1.<method>()wraps the frame and calls the method ofPolarsLaps, thenPolarsTelemetry, thenPolarsSessionResults, in that order of lookup.df.f1.as_laps(session=None),df.f1.as_telemetry(session=None, driver=None), anddf.f1.as_results(session=None)return the wrapped frame.- The session comes from the frame when it is a tif1 class (
df.f1.session). A plain frame fromfilter()has no session. Passsession=to every method that fetches telemetry. Without a session,df.f1.telemetry,get_telemetry(),get_car_data(),get_pos_data(), andadd_track_status()raise aValueErrorthat names thesession=keyword. The laps that adf.f1call returns carry no session either, sodf.f1.pick_fastest().get_telemetry()raises the same error. For thetelemetryproperty, usedf.f1.as_laps(session).telemetry.
Type Hints and IDE Support
The model classes work as type annotations for IDE integration, autocomplete, and type checking. Many of their methods have no return annotations, so a type checker infers less there.Type Annotations
Performance Considerations
Lazy Loading
All models use lazy loading for optimal performance:Filtering Methods
Thepick_* methods run the same vectorized pandas filters as hand-written masks, in fewer lines:
Best Practices
1. Check for Empty Data
Always check if data is available before processing:2. Use Method Chaining
Chain filtering methods for readable code:3. Handle Exceptions Properly
Use specific exception types for better error handling:Summary
The models module provides a complete, simple API for F1 data analysis:Key Takeaways
- Laps: Primary interface for lap timing data with flexible filtering methods
- Lap: Single lap with telemetry access and timing information
- Driver: The results row of a driver, with access to all their laps
- Telemetry: High-frequency sensor data with slicing and analysis methods
- SessionResults: Race results and final standings
- DriverResult: Individual driver’s race result
- CircuitInfo: Circuit layout information and track markers
Core Principles
- Lazy Loading: Data loaded on-demand for performance
- Method Chaining: Fluent API for readable code
- Type Hints: The classes work as type annotations
- FastF1 Compatible: Easy migration from FastF1
- Two Backends: pandas classes, and polars classes with the same methods
- Performance Optimized: Vectorized operations and caching
Related Pages
Core API
Session and data loading methods.
Types
Type definitions and schemas.
Data Schema
Complete data structure reference.
Examples
Real-world usage examples.