Skip to content

to_canonical_station_vehicle_counts

to_canonical_station_vehicle_counts

to_canonical_station_vehicle_counts(raw: dict, *, system_id: str, fetched_at: Timestamp | None = None) -> DataFrame

Melt per-vehicle-type availability from station_status into a long frame.

GBFS 2.2+/3.x stations may report vehicle_types_available (a list of {vehicle_type_id, count}). This explodes it to one row per station × vehicle type (STATION_VEHICLE_COUNTS_COLUMNS), so "where are the e-bikes?" is a join to to_canonical_vehicle_types; the aggregate num_bikes_available cannot answer it. Stations without the field contribute no rows.

See Also

to_canonical_station_status : The aggregate status parser. to_canonical_vehicle_types : Resolve the vehicle types counted.

Source code in src/gbfs_toolkit/io/normalize.py
def to_canonical_station_vehicle_counts(
    raw: dict,
    *,
    system_id: str,
    fetched_at: pd.Timestamp | None = None,
) -> pd.DataFrame:
    """Melt per-vehicle-type availability from ``station_status`` into a long frame.

    GBFS 2.2+/3.x stations may report ``vehicle_types_available`` (a list of
    ``{vehicle_type_id, count}``). This explodes it to one row per station × vehicle type
    (`STATION_VEHICLE_COUNTS_COLUMNS`), so "where are the e-bikes?"
    is a join to [`to_canonical_vehicle_types`][gbfs_toolkit.to_canonical_vehicle_types]; the aggregate ``num_bikes_available``
    cannot answer it. Stations without the field contribute no rows.

    See Also
    --------
    [`to_canonical_station_status`][gbfs_toolkit.to_canonical_station_status] : The aggregate status parser.
    [`to_canonical_vehicle_types`][gbfs_toolkit.to_canonical_vehicle_types] : Resolve the vehicle types counted.
    """
    fetched_at = fetched_at if fetched_at is not None else _now_utc()
    data = raw.get("data", raw)
    stations = _records(data, "stations")
    rows = [
        {
            "system_id": system_id,
            "station_id": str(s.get("station_id")),
            "vehicle_type_id": str(vt.get("vehicle_type_id")),
            "num_vehicles_available": vt.get("count"),
            "fetched_at": fetched_at,
        }
        for s in stations
        for vt in (s.get("vehicle_types_available") or [])
    ]
    df = pd.DataFrame(rows, columns=STATION_VEHICLE_COUNTS_COLUMNS)
    df["num_vehicles_available"] = pd.to_numeric(
        df["num_vehicles_available"], errors="coerce"
    ).astype("Int64")
    df["vehicle_type_id"] = df["vehicle_type_id"].astype(
        "string"
    )  # join key, see to_canonical_vehicles
    df["fetched_at"] = pd.to_datetime(df["fetched_at"], utc=True)
    return df