Skip to content

coerce_schema

coerce_schema

coerce_schema(df: DataFrame, schema: str) -> DataFrame

Cast a frame's columns to the canonical dtypes for schema (nullable ints/bools, UTC).

Best-effort: only columns present are touched; unparseable values become pd.NA/NaT. Handy after reading frames from CSV or a third-party source before feeding the toolkit.

See Also

validate_schema : Validate without coercing. SchemaError : Raised on an irreconcilable schema.

Source code in src/gbfs_toolkit/core/models.py
def coerce_schema(df: pd.DataFrame, schema: str) -> pd.DataFrame:
    """Cast a frame's columns to the canonical dtypes for ``schema`` (nullable ints/bools, UTC).

    Best-effort: only columns present are touched; unparseable values become ``pd.NA``/``NaT``.
    Handy after reading frames from CSV or a third-party source before feeding the toolkit.

    See Also
    --------
    [`validate_schema`][gbfs_toolkit.validate_schema] : Validate without coercing.
    [`SchemaError`][gbfs_toolkit.SchemaError] : Raised on an irreconcilable schema.
    """
    out = df.copy()
    for col in _schema_columns(schema):
        if col not in out.columns:
            continue
        if col in _DATETIME_COLUMNS:
            out[col] = pd.to_datetime(out[col], utc=True, errors="coerce")
        elif col in _CANONICAL_DTYPES:
            dtype = _CANONICAL_DTYPES[col]
            if dtype in ("Int64", "float64"):
                out[col] = pd.to_numeric(out[col], errors="coerce").astype(dtype)
            else:
                out[col] = out[col].astype(dtype)
    return out