Use this file to discover Exa products, pricing, evaluations, comparisons, use cases, agent interfaces, and technical documentation before exploring further.
Python geospatial libraries read, analyze, and transform data tied to locations on Earth, such as points, boundaries, and satellite images. Vector data stores each shape as coordinates rather than as the grid of cell values that raster data uses. These libraries let mapping apps, logistics tools, and AI agents answer questions about places and distances.
Popularity
Shapely has the most monthly downloads in this comparison, at 78.4M.
def _to_file_fiona(df, filename, driver, schema, crs, mode, metadata, **kwargs):
if not HAS_PYPROJ and crs:
raise ImportError(
"The 'pyproj' package is required to write a file with a CRS, but it is not"
" installed or does not import correctly."
)
if schema is None:
schema = infer_schema(df)
if crs:
from pyproj import CRS
crs = CRS.from_user_input(crs)
else:
crs = df.crs
with fiona_env():
crs_wkt = None
try:
gdal_version = Version(
fiona.env.get_gdal_release_name().strip("e")
) # GH3147
except (AttributeError, ValueError):
gdal_version = Version("2.0.0") # just assume it is not the latest
if gdal_version >= Version("3.0.0") and crs:
crs_wkt = crs.to_wkt()
elif crs:
crs_wkt = crs.to_wkt("WKT1_GDAL")
with fiona.open(
filename, mode=mode, driver=driver, crs_wkt=crs_wkt, schema=schema, **kwargs
) as colxn:
if metadata is not None:
colxn.update_tags(metadata)
colxn.writerecords(df.iterfeatures())
h3-py
Indexes locations with the Uber hierarchical hexagonal geospatial indexing system.
@sequential_deduplication
def linetrace(geometry: MultiLineOrLine, resolution: int) -> Iterator[str]:
"""h3.polyfill equivalent for shapely (Multi)LineString
Does not represent lines with duplicate sequential cells,
but cells may repeat non-sequentially to represent
self-intersections
Parameters
---------- geometry : LineString or MultiLineString
Line to trace with H3 cells
resolution : int
H3 resolution of the tracing cells
Returns
------- Set of H3 addresses
Raises
------ TypeError if geometry is not a LineString or a MultiLineString
"""
if isinstance(geometry, MultiLineString):
# Recurse after getting component linestrings from the multiline for line in map(lambda geom: linetrace(geom, resolution), geometry.geoms):
yield from line
elif isinstance(geometry, LineString):
coords = zip(geometry.coords, geometry.coords[1:])
while (vertex_pair := next(coords, None)) is not None:
i, j = vertex_pair
a = h3.latlng_to_cell(*i[::-1], resolution)
b = h3.latlng_to_cell(*j[::-1], resolution)
yield from h3.grid_path_cells(a, b) # inclusive of a and b
else:
raise TypeError(f"Unknown type {type(geometry)}")
GeoPandas
Extends pandas with geometry columns, spatial operations, and geospatial file handling.
Downloads / mo
14.8M
Stars
5.3K
Last release
1.2.0
License
BSD-3-Clause
Strengths
Combines geometry with table columns.Retain attributes from both tables when overlaying spatial datasets.
Reprojects geometry columns.Use to_crs to transform the active geometry column.
Limitations
Dateline crossings distort reprojection.Check geometries that cross the dateline or other projection boundaries.
def project_gdf(
gdf: gpd.GeoDataFrame,
*,
to_crs: Any | None = None, # noqa: ANN401
to_latlong: bool = False,
) -> gpd.GeoDataFrame:
"""
Project a GeoDataFrame from its current CRS to another.
If `to_latlong` is True, this projects the GeoDataFrame to the coordinate
reference system defined by `settings.default_crs`. Otherwise it projects
it to the CRS defined by `to_crs`. If `to_crs` is `None`, it projects it
to the CRS of an appropriate UTM (or UPS) zone given `gdf`'s bounds.
Parameters
---------- gdf
The GeoDataFrame to be projected.
to_crs
If None, project to an appropriate UTM zone. Otherwise project to
this CRS.
to_latlong
If True, project to `settings.default_crs` and ignore `to_crs`.
Returns
------- gdf_proj
The projected GeoDataFrame.
"""
if gdf.crs is None or len(gdf) == 0: # pragma: no cover
msg = "`gdf` must have a valid CRS and cannot be empty."
raise ValueError(msg)
# if to_latlong is True, project the gdf to the default_crs if to_latlong:
to_crs = settings.default_crs
# else if to_crs is None, choose an appropriate UTM zone elif to_crs is None:
UTM_NORTH_LIMIT = 84
UTM_SOUTH_LIMIT = -80
centroid = gdf.union_all().centroid
# if gdf is already projected, temporarily re-project centroid to # lat-long to check against UTM (lat-long) north/south limits if is_projected(gdf.crs):
centroid, _ = project_geometry(centroid, crs=gdf.crs, to_latlong=True)
# if centroid is north or south of UTM limits, use UPS CRS instead if centroid.y < UTM_SOUTH_LIMIT:
to_crs = "epsg:32761"
elif centroid.y > UTM_NORTH_LIMIT:
to_crs = "epsg:32661"
else:
# otherwise, we're within UTM limits, so choose a UTM zone to_crs = gdf.estimate_utm_crs()
# project the gdf gdf_proj = gdf.to_crs(to_crs)
crs_desc = f"{gdf_proj.crs.to_string()} / {gdf_proj.crs.name}"
msg = f"Projected GeoDataFrame to {crs_desc!r}"
utils.log(msg, level=lg.INFO)
return gdf_proj
Pyogrio
Reads and writes spatial vector file formats in vectorized form through GDAL and OGR.
def _to_file_pyogrio(df, filename, driver, schema, crs, mode, metadata, **kwargs):
import pyogrio
if schema is not None:
raise ValueError(
"The 'schema' argument is not supported with the 'pyogrio' engine."
)
if mode == "a":
kwargs["append"] = True
if crs is not None:
raise ValueError("Passing 'crs' is not supported with the 'pyogrio' engine.")
# for the fiona engine, this check is done in gdf.iterfeatures() if not df.columns.is_unique:
raise ValueError("GeoDataFrame cannot contain duplicated column names.")
pyogrio.write_dataframe(df, filename, driver=driver, metadata=metadata, **kwargs)
def bounds_tree(bounds: ArrayLike) -> Any:
"""
Given a set of axis aligned bounds create an r-tree for
broad-phase collision detection.
Parameters
------------ bounds : (n, 2D) or (n, 2, D) float
Non-interleaved bounds where D=dimension
E.G a 2D bounds tree:
[(minx, miny, maxx, maxy), ...]
Returns
--------- tree : Rtree
Tree containing bounds by index
"""
import rtree
# make sure we've copied bounds bounds = np.array(bounds, dtype=np.float64, copy=True)
if len(bounds.shape) == 3:
# should be min-max per bound if bounds.shape[1] != 2:
raise ValueError("bounds not (n, 2, dimension)!")
# reshape to one-row-per-hyperrectangle bounds = bounds.reshape((len(bounds), -1))
elif len(bounds.shape) != 2 or bounds.size == 0:
raise ValueError("Bounds must be (n, dimension * 2)!")
# check to make sure we have correct shape dimension = bounds.shape[1]
if (dimension % 2) != 0:
raise ValueError("Bounds must be (n,dimension*2)!")
dimension = int(dimension / 2)
properties = rtree.index.Property(dimension=dimension)
# stream load was verified working on import above return rtree.index.Index(
zip(np.arange(len(bounds)), bounds, [None] * len(bounds)), properties=properties
)
def _query(data, forward, provider, throttle_time, **kwargs):
# generic wrapper for calls over lists to geopy Geocoders from geopy.geocoders import get_geocoder_for_service
from geopy.geocoders.base import GeocoderQueryError
if forward:
if not isinstance(data, pd.Series):
data = pd.Series(data)
else:
if not isinstance(data, geopandas.GeoSeries):
data = geopandas.GeoSeries(data)
if isinstance(provider, str):
provider = get_geocoder_for_service(provider)
coder = provider(**kwargs)
results = {}
for i, s in data.items():
try:
if forward:
results[i] = coder.geocode(s)
else:
results[i] = coder.reverse((s.y, s.x), exactly_one=True)
except (GeocoderQueryError, ValueError):
results[i] = (None, None)
time.sleep(throttle_time)
df = _prepare_geocode_result(results)
return df
Rasterio
Reads and writes geospatial raster datasets through NumPy-based Python APIs.
Downloads / mo
7.4M
Stars
2.6K
Last release
1.5.2
License
BSD-3-Clause
Strengths
Works directly with raster arrays.Read and write pixel bands as array data.
Reprojects raster grids.Use reproject to map arrays into another geospatial grid.
Limitations
Writing support varies by driver.Use GeoTIFF for the best-supported writing path.
def point(
src_dst: DatasetReader | DatasetWriter | WarpedVRT,
coordinates: tuple[float, float],
indexes: Indexes | None = None,
coord_crs: CRS = WGS84_CRS,
nodata: NoData | None = None,
vrt_options: dict | None = None,
out_dtype: str | numpy.dtype | None = None,
resampling_method: RIOResampling = "nearest",
reproject_method: WarpResampling = "nearest",
interpolate: bool = False,
unscale: bool = False,
post_process: Callable[[numpy.ma.MaskedArray], numpy.ma.MaskedArray] | None = None,
) -> PointData:
"""Read a pixel value for a point.
Args:
src_dst (rasterio.io.DatasetReader or rasterio.io.DatasetWriter or rasterio.vrt.WarpedVRT): Rasterio dataset.
coordinates (tuple): Coordinates in form of (X, Y).
indexes (sequence of int or int, optional): Band indexes.
coord_crs (rasterio.crs.CRS, optional): Coordinate Reference System of the input coords. Defaults to `epsg:4326`.
nodata (int or float, optional): Overwrite dataset internal nodata value.
vrt_options (dict, optional): Options to be passed to the rasterio.warp.WarpedVRT class.
resampling_method (RIOResampling, optional): RasterIO resampling algorithm. Only used when `interpolate=True`. Defaults to `nearest`.
reproject_method (WarpResampling, optional): WarpKernel resampling algorithm. Defaults to `nearest`.
interpolate (bool, optional): Interpolate pixels around the coordinates. Defaults to `False`.
unscale (bool, optional): Apply dataset's 'scales' and 'offsets' on output data value. Defaults to `False`.
post_process (callable, optional): Function to apply on output data and mask values.
Returns:
PointData
"""
indexes = cast_to_sequence(indexes)
with contextlib.ExitStack() as ctx:
# Use WarpedVRT when User provided Nodata or VRT Option (cutline) if nodata is not None or vrt_options:
vrt_params = {
"add_alpha": True,
"resampling": Resampling[reproject_method],
"dtype": src_dst.dtypes[0],
}
nodata = nodata if nodata is not None else src_dst.nodata
if nodata is not None:
vrt_params.update(
{"nodata": nodata, "add_alpha": False, "src_nodata": nodata}
)
if has_alpha_band(src_dst):
vrt_params.update({"add_alpha": False})
if vrt_options:
vrt_params.update(**vrt_options)
dataset = ctx.enter_context(WarpedVRT(src_dst, **vrt_params))
else:
dataset = src_dst
lon, lat = coordinates
if coord_crs != dataset.crs:
xs, ys = transform_coords(coord_crs, dataset.crs, [lon], [lat])
lon, lat = xs[0], ys[0]
dataset_min_lon, dataset_min_lat, dataset_max_lon, dataset_max_lat = (
dataset.bounds
)
# check if latitude is inverted if dataset_min_lat > dataset_max_lat:
warnings.warn(
"BoundingBox of the dataset is inverted (minLat > maxLat).",
UserWarning,
)
dataset_min_lat, dataset_max_lat = (
min(dataset_min_lat, dataset_max_lat),
max(dataset_min_lat, dataset_max_lat),
)
if not (
(dataset_min_lon < lon < dataset_max_lon)
and (dataset_min_lat < lat < dataset_max_lat)
):
raise PointOutsideBounds("Point is outside dataset bounds")
if interpolate:
# Ref: https://github.com/cogeotiff/rio-tiler/issues/793 # https://github.com/OSGeo/gdal/blob/a3d68b069e6b3676ba437faca5dca6ae2076ce24/swig/python/gdal-utils/osgeo_utils/samples/gdallocationinfo.py#L185-L197 rows, cols = rowcol(dataset.transform, xs=[lon], ys=[lat], op=lambda x: x)
row, col = float(rows[0]), float(cols[0])
row_off, col_off = row - 0.5, col - 0.5
else:
if resampling_method != "nearest":
warnings.warn(
f"{resampling_method} resampling will be ignored when `interpolate=False`.",
UserWarning,
)
row, col = dataset.index(lon, lat)
row_off, col_off = row, col
window = windows.Window(row_off=row_off, col_off=col_off, width=1, height=1)
img = read(
dataset,
indexes=indexes,
window=window,
out_dtype=out_dtype,
resampling_method=resampling_method,
unscale=unscale,
post_process=post_process,
)
return PointData(
img.array[:, 0, 0],
band_names=img.band_names,
band_descriptions=img.band_descriptions,
coordinates=coordinates,
crs=coord_crs,
pixel_location=(col, row),
nodata=img.nodata,
metadata=img.metadata,
)
FAQ
GeoPandas suits most vector analysis, with geometry columns on a pandas DataFrame. Shapely suits operations on individual geometries. Rasterio suits satellite images and other raster datasets.
GeoPandas extends pandas with geometry columns, spatial operations, and reading and writing of geospatial files.
Shapely manipulates and analyzes geometric objects such as points, lines, and polygons in a Cartesian plane. pyproj handles transformations between coordinate systems.
geopy is a geocoding toolbox that turns addresses into coordinates and coordinates into addresses through outside geocoding services.
Rasterio reads and writes geospatial raster datasets as NumPy arrays.
For coding agents
Found your geospatial library? Help your agent use it.
Connect Exa so your coding agent can find the library’s documentation, check its API, and look up implementations while you build.