GeoPandas Polygon – Converting Geometry from Bounds to Polygon Using GeoPandas

geopandaspolygonpython

I have a GeoPandas DataFrame with bounds geometry.

import pandas as pd
import geopandas as gpd

gdf = gpd.GeoDataFrame({
                        'id': [0, 1],
                        'b': [((40.6494140625, -86.7919921875), (40.69335937...)), 
                              ((39.55078125, -93.8232421875), (39.5947265625...))]
                      })

gdf['b'][0]

Bounds(sw=SouthWest(lat=32.8271484375, lon=-96.8115234375), ne=NorthEast(lat=32.87109375, lon=-96.767578125))

print(type(gdf['b'][0]))

<class 'geolib.geohash.Bounds'>

How do I turn Bounds into Polygon geometry type?

Like,

Polygon((40.6494140625, -86.7919921875), (40.69335937...))

Best Answer

Use shapely box

import geopandas as gpd
from shapely.geometry import box
lines = gpd.read_file("lines.shp")  
# total bounds of the shapefile       
xmin,ymin,xmax,ymax =  lines.total_bounds
print(xmin,ymin,xmax,ymax)
202611.93416148185 88948.08685124904 203905.81262856247 90209.61835665265
# convert to polygon
geom =box(*lines.total_bounds)
print(geom)
POLYGON ((203905.8126285625 88948.08685124904, 203905.8126285625 90209.61835665265, 202611.9341614819 90209.61835665265, 202611.9341614819 88948.08685124904, 203905.8126285625 88948.08685124904))

The shapefile and the total_bounds polygon:

enter image description here