Models API Reference
The models module provides a comprehensive, object-oriented interface for working with Formula 1 data. These classes extend pandas DataFrame and Series objects with domain-specific methods tailored for F1 analysis, making it intuitive to filter, analyze, and visualize racing data with minimal code.Overview
All model classes in tif1 are built on top of pandas data structures, providing familiar DataFrame and Series interfaces while adding specialized methods for F1 data manipulation. This design philosophy allows you to leverage the full power of pandas operations alongside tif1-specific functionality, creating a seamless development experience.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: Full type annotation support for enhanced IDE autocomplete and type checking
- Automatic Validation: Built-in data validation and error handling
- Dual Backend Support: Works with both pandas and polars backends (where applicable)
- Zero-Copy Operations: Optimized for performance with minimal data duplication
- Thread-Safe Caching: Internal caching mechanisms for repeated access patterns
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:- Intuitive Access Patterns: Natural property access (e.g.,
lap.telemetry,driver.laps) - Consistent Filtering: All filtering methods follow the
pick_*naming convention - Graceful Degradation: Methods return empty DataFrames instead of raising exceptions when data is unavailable
- Session Context: All models maintain a reference to their parent session for seamless data access
- Performance First: Optimized for speed with vectorized operations and intelligent 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 (re-exported from tif1.core)
Thread Safety: Read operations are thread-safe; write operations should be synchronized externally
Common Access Patterns
TheLaps class can be accessed through multiple pathways depending on your analysis needs:
Data Structure
Each row in aLaps DataFrame represents a single lap with comprehensive timing and metadata. The DataFrame contains the following column categories:
Core Identity Columns
Driver(str): 3-letter driver code (e.g., “VER”, “HAM”, “LEC”)DriverNumber(str): Car racing number (e.g., “1”, “44”, “16”)Team(str): Full team name (e.g., “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(str): 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(str): Track condition code (“1”=Green, “2”=Yellow, “4”=Safety Car, “5”=Red Flag, “6”=VSC, “7”=VSC Ending)Position(float): Track position at lap completionIsPersonalBest(bool): Whether this is the driver’s fastest lapDeleted(bool): 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”)
Derived Columns
LapTimeSeconds(float): Lap time in seconds (derived from LapTime for convenience)
Weather Data (per-lap)
When weather data is available, each lap includes: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 km/hWindDirection(int): Wind direction in degreesRainfall(bool): Whether it’s raining
Properties
Session
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:
Core Filtering Methods
The Laps class provides a comprehensive 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 (e.g., “VER”, “HAM”, “LEC”) - most common usageint: Driver racing number (e.g., 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 (must use uppercase: “VER” not “ver”)
- 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: List of driver identifiers (same formats aspick_driver). Can mix different identifier types in the same list.
Lapsobject containing laps from all specified drivers. Returns empty Laps if no matching drivers found.
- Accepts mixed identifier types in the same list (e.g.,
["VER", 44, {"driver": "LEC"}]) - Order of drivers in result matches original lap chronological order, not identifier order
- Duplicate identifiers are automatically deduplicated
- 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): Reserved for future use. Currently has no effect. In FastF1, this parameter controls whether to consider only lap time or also track status. In tif1, only lap time is considered.
Lapobject representing the fastest lap, orNoneif no valid laps found
- Only considers laps with valid lap times (non-null, non-NaN)
- Returns the lap with the minimum
LapTimevalue - Returns
Noneif the collection is empty or has no valid lap times - 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=1.07)
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, default=1.07): Percentage multiplier for the fastest lap time. Default is 1.07 (107%), which is the F1 qualifying 107% rule. Must be >= 1.0.
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 - Only considers laps with valid lap times (non-null, non-NaN)
- Returns empty Laps 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(list[str]): List of tire compound names forpick_compounds
Lapsobject containing only laps on the specified compound(s)
- Compound names are case-sensitive (use uppercase)
- 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(laps)
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: Can be:int: Single lap numberlist[int]: Multiple specific lap numbersslice: Range of laps (e.g.,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 doesn’t exist
pick_lapis a convenience wrapper forpick_lapswith a single lap- 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 (e.g., “Red Bull Racing”, “Mercedes”, “Ferrari”)names(list[str]): List of team names forpick_teams
Lapsobject containing only laps from the specified team(s)
- Team names must match exactly (case-sensitive)
- 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:- “equals” (default): Exact match
- “contains”: Partial match (useful for complex status codes)
Lapsobject containing only laps with the specified track status
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 empty Laps if columns don’t exist
pick_not_deleted() / pick_accurate()
Filter for valid and accurate laps. Essential for ensuring data quality in analysis.
pick_not_deleted(): Laps that weren’t 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 doesn’t exist
Telemetry Access Methods
get_telemetry() / telemetry property
Access high-frequency telemetry data for the laps in the collection. This is one of the most powerful features of tif1, enabling detailed analysis of driver inputs and car behavior.
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)telemetryproperty provides basic telemetry without driver-ahead data- Returns empty Telemetry if no data available
- Automatically concatenates telemetry from all laps in the collection
- 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.
TelemetryDataFrame (same astelemetryproperty)
get_car_data()returns full telemetry dataget_pos_data()returns position data (same as car data in tif1)- Both methods accept
**kwargsfor FastF1 compatibility (ignored in tif1) - For multi-driver laps, concatenates telemetry from all laps
get_weather_data()
Get weather data for the laps. Returns session-level weather information.
DataFramewith weather data from the session
- Returns session-level weather data (not lap-specific)
- Returns empty DataFrame if weather data unavailable
- Weather data includes: AirTemp, TrackTemp, Humidity, Pressure, WindSpeed, WindDirection, Rainfall
Iteration Methods
iterlaps(require=None)
Iterate over laps with optional required columns. This is the recommended way to iterate over laps when you need 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. Default is["LapTime", "Driver"].
_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
- Removes null columns from each lap before yielding
- Preserves session context in yielded Lap objects
- Raises
KeyErrorif a required column doesn’t exist in the DataFrame
- 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. Note: tif1 doesn’t split by session internally, so this returns copies for FastF1 compatibility.
tuple[Laps, Laps, Laps]: (Q1 laps, Q2 laps, Q3 laps)
- Returns three Laps objects representing Q1, Q2, and Q3
- In tif1, this returns copies of the same data for compatibility
- Each returned Laps object preserves session context
- If
QualifyingSessioncolumn exists, attempts to split by that column
DataFrame Operations
TheLaps class inherits all pandas DataFrame operations, so you can use standard pandas methods:
Lap
TheLap class represents a single lap with comprehensive timing data and access to high-frequency telemetry. It inherits from pandas.Series, making it a row-like object with named fields that can be accessed like a dictionary or via attribute access.
Class Overview
Inheritance:pandas.Series → Lap
Module: tif1.models (re-exported from tif1.core)
Common Access Patterns:
Data Structure
ALap object is a pandas Series containing all the lap data columns described in the Laps section. You can access any column value using dictionary-style or attribute-style access:
Properties
int
The lap number extracted from the Note: Returns
LapNumber column. This is a convenience property that returns the lap number as an integer.Usage:None if LapNumber column is missing or null.str
The 3-letter driver code extracted from the Note: Returns
Driver column. This identifies which driver completed this lap.Usage:None if Driver column is missing or null.Telemetry
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 you access this property)
- 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 network request (~50-200ms depending on connection)
- Subsequent accesses are instant (cached in memory)
- Telemetry data is typically 1000-3000 samples per lap
Session
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()
Explicitly load telemetry data with driver-ahead channels. This method is similar to accessing the telemetry property but includes additional channels for analyzing car-to-car interactions.
TelemetryDataFrame with all telemetry channels including:- Standard channels: Time, 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.
**kwargs: Accepts any keyword arguments for FastF1 compatibility (ignored in tif1)
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
get_weather_data()
Get weather data for this lap. Currently returns an empty Series as lap-specific weather data is included in the lap’s columns.
Series: Empty pandas Series (weather data is in lap columns)
- Provided for FastF1 compatibility
- Weather data is already available in lap columns (AirTemp, TrackTemp, Humidity, etc.)
- Returns empty Series in current implementation
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, providing access to their metadata, all their laps, and convenience methods for analyzing their performance. It inherits from pandas.Series, making it a dictionary-like object with driver information.
Class Overview
Inheritance:pandas.Series → Driver
Module: tif1.models (re-exported from tif1.core)
Common Access Patterns:
Data Structure
ADriver object is a pandas Series containing driver metadata. 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 (e.g., “1”, “44”, “16”)Abbreviation(str): 3-letter driver code (e.g., “VER”, “HAM”, “LEC”)TeamName(str): Full team name (e.g., “Red Bull Racing”, “Mercedes”)TeamColor(str): Team color hex code (e.g., “#3671C6”)FirstName(str): Driver’s first name (e.g., “Max”, “Lewis”)LastName(str): Driver’s last name (e.g., “Verstappen”, “Hamilton”)FullName(str): Driver’s full name (e.g., “Max Verstappen”)HeadshotUrl(str): URL to driver headshot image
Properties
str
The 3-letter driver code (e.g., “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.
Session
Reference to the parent Session object. This maintains the connection to the session, enabling access to session-level data and methods.Usage:
Laps | DataFrame
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 DataFrame (polars backend)Behavior:- Loaded lazily on first access (not fetched until you access this property)
- 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 network request if not cached (~50-200ms)
- 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 positive integer.
Lapobject for the specified lap
LapNotFoundError: If the lap doesn’t exist for this driverValueError: If lap_number is invalid (negative, zero, or not an integer)
- 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 extremely 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)
- Returns the lap with minimum
LapTimevalue - Returns empty DataFrame (not None) if no valid laps exist
- Result is a DataFrame (not a Lap object) for consistency with FastF1
- 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 is one of the most powerful classes in tif1, enabling detailed analysis of driver inputs, car behavior, and racing lines.
Class Overview
Inheritance:pandas.DataFrame → Telemetry
Module: tif1.models (re-exported from tif1.core)
Sampling Rate: Typically 10-20 Hz (10-20 samples per second), resulting in 1000-3000 samples per lap
Common Access Patterns:
Properties
Session
Reference to the parent Session object. Maintains connection to the session for accessing session-level data.
str
Driver code for this telemetry data (e.g., “VER”, “HAM”). May be None if telemetry is from multiple drivers.
Available Columns
Telemetry DataFrames contain high-frequency sensor data with the following columns:Time and Distance
Speed and Engine
Driver Inputs
Position (3D Coordinates)
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)end_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): Whether to interpolate at slice boundaries (reserved for future use)
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 doesn’t 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): Whether to interpolate at boundaries
TelemetryDataFrame for the specified lap(s)
- Extracts telemetry based on lap start/end times or lap numbers
- 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. Powerful 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 doesn’t 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
- Converts speed from km/h to m/s internally
- Returns original telemetry if Distance already exists
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)
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)
- Currently returns placeholder data (not fully implemented in tif1)
- Provided for FastF1 compatibility
- Future versions will include actual driver-ahead calculations
Data Processing Methods
fill_missing()
Interpolate missing values in numeric columns. Useful for cleaning telemetry data.
Telemetrywith interpolated values
- Interpolates all numeric columns
- Uses linear interpolation
- Fills in both directions (forward and backward)
merge_channels(other, **kwargs)
Merge telemetry from another source using time-based alignment.
other: Another Telemetry or DataFrame to merge**kwargs: Additional arguments (for compatibility)
Telemetrywith merged channels
- Uses time-based alignment (merge_asof)
- Aligns on Time column
- Adds suffix “_other” to conflicting columns
resample_channels(rule="1S", **kwargs)
Resample telemetry to a different frequency. Useful for reducing data size or standardizing sampling rates.
rule(str, default=“1S”): Resampling frequency (e.g., “1S” = 1 second, “100ms” = 100 milliseconds)**kwargs: Additional arguments (for compatibility)
Telemetryresampled to specified frequency
- Resamples numeric columns using mean aggregation
- Interpolates missing values after resampling
- Useful for reducing data size or aligning different telemetry sources
Common Usage Patterns
Basic Telemetry Analysis
Comparing Two Laps
Finding Braking Points
SessionResults
TheSessionResults class contains race results and final standings for a session. It inherits from pandas.DataFrame, providing a tabular view of how drivers finished the session.
Class Overview
Inheritance:pandas.DataFrame → SessionResults
Module: tif1.models (re-exported from tif1.core)
Common Access Patterns:
Properties
Session
Reference to the parent Session object. Maintains connection to the session for accessing session-level data.
Available Columns
The SessionResults DataFrame typically contains the following columns:
Note: Column availability depends on session type and data source.
Usage Examples
Basic Results Access
Analyzing Results
DriverResult
TheDriverResult class represents an individual driver’s race result. It inherits from pandas.Series, making it a single row from the SessionResults DataFrame.
Class Overview
Inheritance:pandas.Series → DriverResult
Module: tif1.models (re-exported from tif1.core)
Common Access Patterns:
Properties
Session
Reference to the parent Session object.
int/float
Final position (available in Series data). Access via
driver_result['Position'].str
Driver code (available in Series data). Access via
driver_result['Driver'].int/float
Points earned (available in Series data). Access via
driver_result['Points'].str
Finish status (available in Series data). Access via
driver_result['Status'].bool
Whether the driver did not finish (computed property). Returns True if status indicates DNF, retirement, or disqualification.Behavior:
- Returns
Trueif status is NOT one of: “Finished”, “+1 Lap”, “+2 Laps”, “Not classified” - Returns
Falseotherwise - 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.
Class Overview
Type: Dataclass Module:tif1.models (re-exported from tif1.core)
Common Access Patterns:
Properties
DataFrame
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 (if applicable)Angle(float): Corner angle in degreesDistance(float): Distance along track (populated afteradd_marker_distance())
DataFrame
Location of marshal lights (always empty in tif1 - not available in source data). Provided for FastF1 compatibility.Note: This data is not available through the tif1 data source. The DataFrame will always be empty but maintains the correct column schema.
DataFrame
Location of marshal sectors (always empty in tif1 - not available in source data). Provided for FastF1 compatibility.Note: This data is not available through the tif1 data source. The DataFrame will always be empty but maintains the correct column schema.
float
Rotation of the circuit in degrees. Default is 0.0.Usage:
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 DataFrame 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: Comprehensive Race Analysis
Example 2: Telemetry Comparison Visualization
Example 3: Tire Degradation Analysis
Type Hints
All models support type hints for better IDE integration.Summary
The models module provides:- Object-oriented interface for F1 data
- Lazy loading for performance
- Convenient methods for common operations
- Type hints for IDE support
- DataFrame-based data access
Related Pages
Core API
Session and Driver
Types
Type definitions
Data Schema
Data structure
Examples
Usage examples
Type Hints and IDE Support
All models support comprehensive type hints for better IDE integration, autocomplete, and type checking. This makes development faster and reduces errors.Type Annotations
Performance Considerations
Lazy Loading
All models use lazy loading for optimal performance:Efficient Filtering
Use tif1’s filtering methods instead of pandas operations for better performance: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 comprehensive, intuitive API for F1 data analysis:Key Takeaways
- Laps: Primary interface for lap timing data with powerful filtering methods
- Lap: Single lap with telemetry access and timing information
- Driver: Driver metadata 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 Safety: Full type hints for IDE support
- FastF1 Compatible: Easy migration from FastF1
- Pandas-Based: Familiar DataFrame/Series interface
- Performance Optimized: Vectorized operations and intelligent 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