Skip to content

to_canonical_vehicles

to_canonical_vehicles

to_canonical_vehicles(raw: dict, *, system_id: str, gbfs_version: str = '2.x', fetched_at: Timestamp | None = None) -> DataFrame

Parse free_bike_status (2.x) or vehicle_status (3.x) into a canonical frame.

Returns VEHICLE_STATUS_COLUMNS.

See Also

to_canonical_vehicle_types : Resolve each vehicle's type. to_canonical_pricing_plans : Resolve each vehicle's pricing.

Source code in src/gbfs_toolkit/io/normalize.py
def to_canonical_vehicles(
    raw: dict,
    *,
    system_id: str,
    gbfs_version: str = "2.x",
    fetched_at: pd.Timestamp | None = None,
) -> pd.DataFrame:
    """Parse ``free_bike_status`` (2.x) or ``vehicle_status`` (3.x) into a canonical frame.

    Returns `VEHICLE_STATUS_COLUMNS`.

    See Also
    --------
    [`to_canonical_vehicle_types`][gbfs_toolkit.to_canonical_vehicle_types] : Resolve each vehicle's type.
    [`to_canonical_pricing_plans`][gbfs_toolkit.to_canonical_pricing_plans] : Resolve each vehicle's pricing.
    """
    fetched_at = fetched_at if fetched_at is not None else _now_utc()
    data = raw.get("data", raw)
    # v3 → "vehicles", v2 → "bikes" (tolerate language nesting)
    items = _records(data, "vehicles", "bikes")
    rows = [
        {
            "system_id": system_id,
            "vehicle_id": str(v.get("vehicle_id") or v.get("bike_id")),
            "station_id": (str(v["station_id"]) if v.get("station_id") is not None else None),
            "vehicle_type_id": v.get("vehicle_type_id"),
            "lat": v.get("lat"),
            "lon": v.get("lon"),
            "is_reserved": bool(v.get("is_reserved", False)),
            "is_disabled": bool(v.get("is_disabled", False)),
            "current_range_meters": v.get("current_range_meters"),
            "current_fuel_percent": v.get("current_fuel_percent"),  # GBFS 3.0: a 0 to 1 fraction
            "pricing_plan_id": v.get("pricing_plan_id"),
            "fetched_at": fetched_at,
            "gbfs_version": gbfs_version,
        }
        for v in items
    ]
    df = pd.DataFrame(rows, columns=VEHICLE_STATUS_COLUMNS)
    for col in ("lat", "lon", "current_range_meters", "current_fuel_percent"):
        df[col] = pd.to_numeric(df[col], errors="coerce")
    for col in ("is_reserved", "is_disabled"):
        df[col] = df[col].astype("boolean")
    # Foreign keys are string-typed so they join against the lookup tables
    # (vehicle_types / pricing_plans), which a numeric id would silently fail to match.
    for col in ("station_id", "pricing_plan_id", "vehicle_type_id"):
        df[col] = df[col].astype("string")
    df["fetched_at"] = pd.to_datetime(df["fetched_at"], utc=True)
    return df