Reading postgis geometry with shapely

The default format for PostGIS geometry is hex-encoded WKB (Well-Known Binary). Shapely has the ability to convert this format into shapely geometry object with its wkb module:

from shapely import wkb

# ....

sql = """SELECT * FROM public.parcels2010_small LIMIT 5;"""
parcels = pd.read_sql(sql, engine)

for parcel in parcels:
    parcel.the_geom = wkb.loads(parcel.the_geom, hex=True)

if you were to then print the geometry it should look something like this:

print parcels[0].the_geom

<shapely.geometry.multipolygon.MultiPolygon object at ...>

See docs on the shapely.wkb module here.


GeoAlchemy understands SQLAlchemy PostGIS and Shapely.

from geoalchemy2.shape import to_shape

for parcel in parcels:
    parcel_shape = to_shape(parcel.the_geom)