Skip to content

to_gdf

to_gdf

to_gdf(df: DataFrame, *, lat: str = 'lat', lon: str = 'lon', crs: str = 'EPSG:4326') -> GeoDataFrame

Convert a frame with lat/lon columns to a GeoPandas GeoDataFrame (lazy import).

Requires the optional [geo] extra (geopandas).

See Also

to_geojson : Serialise to GeoJSON instead. zones_for_points : Assign points to zones.

Source code in src/gbfs_toolkit/spatial/geometry.py
def to_gdf(
    df: pd.DataFrame, *, lat: str = "lat", lon: str = "lon", crs: str = "EPSG:4326"
) -> gpd.GeoDataFrame:
    """Convert a frame with lat/lon columns to a GeoPandas ``GeoDataFrame`` (lazy import).

    Requires the optional ``[geo]`` extra (``geopandas``).

    See Also
    --------
    [`to_geojson`][gbfs_toolkit.to_geojson] : Serialise to GeoJSON instead.
    [`zones_for_points`][gbfs_toolkit.zones_for_points] : Assign points to zones.
    """
    try:
        import geopandas as gpd
    except ImportError as e:  # pragma: no cover
        raise ImportError(
            "to_gdf requires geopandas. Install with `pip install gbfs-toolkit[geo]`."
        ) from e
    geometry = gpd.points_from_xy(df[lon], df[lat])
    return gpd.GeoDataFrame(df.copy(), geometry=geometry, crs=crs)