Skip to content

Instantly share code, notes, and snippets.

@mappingvermont
Created July 21, 2016 21:49
Show Gist options
  • Save mappingvermont/adfb1f3121c127c13e21d04aecfaff20 to your computer and use it in GitHub Desktop.
Save mappingvermont/adfb1f3121c127c13e21d04aecfaff20 to your computer and use it in GitHub Desktop.
Use geopandas to extract south/west/north/east bounding box from a gridded shapefile
import geopandas as gpd
import pandas as pd
shp = gpd.GeoDataFrame.from_file('lossdata_footprint/lossdata_footprint.shp')
# BBox order
# minimum latitude, minimum longitude, maximum latitude, maximum longitude
# (or South-West-North-East).
bbox_dict = {}
# No idea how to use geopandas to get iterate over each feature to
# extract its name and the geometry, but this seems to work
for name_tile, polygon in zip(shp['name_tile'], shp['geometry']):
coords = polygon.exterior.coords[0:4]
output_list = []
for pnt in coords:
x_coord = round(pnt[0])
y_coord = round(pnt[1])
output_list.append((x_coord, y_coord))
min_lat = output_list[0][1]
min_lon = output_list[0][0]
max_lat = output_list[2][1]
max_lon = output_list[2][0]
bbox_dict[name_tile] = [min_lat, min_lon, max_lat, max_lon]
for name_key, bbox in bbox_dict.iteritems():
# query the API
print name_key, bbox
@rvanxer
Copy link

rvanxer commented May 16, 2021

This does not work for me. polygon.exterior.coords returns a LineString object so its first 4 coordinates are really not relevant. I learned from here that you can instead use polygon.envelope.exterior.coords[:4] to get the list of coordinates of the bounding box.

@MATLABmdl
Copy link

Hi

x1,y1,x2,y2 = df.iloc[0].geometry.exterior.bounds

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment