Shapely
Shapely is a BSD-licensed Python package for manipulation and analysis of planar geometric objects. It wraps the widely deployed open-source geometry library GEOS (the engine of PostGIS) to provide both a feature-rich Geometry interface for scalar geometries and high-performance NumPy ufuncs for operations on arrays of geometries. The current version is 2.1.2, with a regular release cadence that includes bug fixes, new features, and compatibility updates for Python and GEOS versions.
Warnings
- breaking Shapely 2.0 introduced a complete internal refactor (merging PyGEOS), making geometries immutable and changing how multi-part geometries behave.
- breaking Direct conversion of geometry objects to NumPy arrays (`np.asarray(geom)`) is deprecated and removed in 2.0.
- breaking The `STRtree` API changed significantly in Shapely 2.0. Operations now return indices of input geometries instead of the geometries themselves.
- deprecated Many function parameters, especially boolean flags like `normalized` or `include_z`, are being transitioned to keyword-only arguments. Passing them positionally is deprecated and raises warnings.
- gotcha When installing Shapely in a Conda environment, installing via `pip install shapely` can sometimes lead to issues with GEOS library discovery, potentially bundling an outdated GEOS.
- gotcha Shapely is a planar geometry library; Z coordinates are generally ignored in geometric analysis, and geometries differing only in Z are not distinguished. `LineString([(0, 0, 0), (0, 0, 1)])` results in an invalid line with zero length.
Install
-
pip install shapely -
conda install shapely --channel conda-forge
Imports
- Point
from shapely import Point
- Polygon
from shapely import Polygon
- box
from shapely import box
- shapely.geometry.Point
from shapely.geometry import Point
- shapely.geos
from shapely import GEOS_VERSION
- shapely.vectorized.contains
from shapely import contains_xy
Quickstart
import shapely
from shapely import Point, Polygon
# Create a point and a polygon
point = Point(0, 0)
polygon = Polygon([(0, 0), (1, 1), (1, 0)])
# Perform a spatial operation
intersection = point.intersection(polygon)
print(f"Point: {point}")
print(f"Polygon: {polygon}")
print(f"Intersection: {intersection}")
print(f"Point within polygon: {polygon.contains(point)}")
# Example of a vectorized operation (Shapely 2.0+)
import numpy as np
geoms = np.array([Point(0.5, 0.5), Point(1.5, 0.5)])
print(f"\nVectorized contains: {shapely.contains(polygon, geoms)}")