5

Using the shapely bounding box function box, and a GeoDataFrameof points, I have extracted a bounding box and created a buffer around it (below gdf is a GeoDataFrameof points):

bbox=shapely.geometry.box(*gdf.geometry.total_bounds)
bbox=bbox.buffer(5)

Now I check and see that bbox is a shapely polygon:

type(bbox)
shapely.geometry.polygon.Polygon

My goal is, from this shapely polygon, to create a 1-row GeoDataFramewith Polygon geometry. I know that I can get all the coordinates that make up this polygon with:

[*bbox.exterior.coords] 

This returns the list of coordinates from a coordinate sequence object which looks like this:

[*bbox.exterior.coords][:5]
[(151.20138500000007, -43.787852999999984),
 (-151.40006999399998, -43.787852999999984),
 (-151.89015569564776, -43.76377663336097),
 (-152.3755216040806, -43.69177940201614),
 (-152.85149338027227, -43.57255467866103)]

However, I cannot seem to figure out how to convert these pairs of coordinates into a GeoDataFrame. I have tried:

crs = {'init': 'epsg:4326'}
polygon = gpd.GeoDataFrame(index=[0], crs=crs, geometry=[*bbox.exterior.coords]) 

which returns the error:

TypeError: Input must be valid geometry objects: (151.20138500000007, -43.787852999999984)

How, then, does one make these coordinate pair tuples into valid geometry objects for a GeoDataFrame?

5
  • Make a shapely polygon geometry from coordinate pairs.
  • Pass the polygon to GeoDataFrame constructor as a list.
    import geopandas as gpd
    from shapely.geometry import Polygon
    
    coords = [(151.20138500000007, -43.787852999999984),
              (-151.40006999399998, -43.787852999999984),
              (-151.89015569564776, -43.76377663336097),
              (-152.3755216040806, -43.69177940201614),
              (-152.85149338027227, -43.57255467866103)]
    
    polygon = Polygon(coords)
    
    gdf = gpd.GeoDataFrame(index=[0], crs='epsg:4326', geometry=[polygon])
    print(gdf)
    
    # OUTPUT
    #                                             geometry
    # 0  POLYGON ((151.20139 -43.78785, -151.40007 -43....
    

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.