# Creating a square buffer around a shapely polygon

I have a list of polygons in a shapefile that I transform into a geopandas dataframe:

polygons = gdp.read_file(polygon_file)


then I would like to create the smallest possible square buffer (in lat-long coordinates) around each of them :

squares = polygons['geometry'].envelope


But of course as they are not circles I get rectangles. Is there an way to create squares instead?

• can't you just move the points so they are the the same distances from each other (ie stretch the rectangle until it is square) and then move it to center it Commented Sep 23, 2020 at 13:21
• actually just stretch it on both sides so you don't have to move it afterwards Commented Sep 23, 2020 at 13:27
• That wont necessarily be the smallest enclosing square.
– Bera
Commented Sep 23, 2020 at 13:33
• stretching is a dangerous operation as I need to verify not to get over the max values for lat and long (90, 180), I'll do it as quick fix but I'm looking for a more elegant way Commented Sep 23, 2020 at 13:36
• yes i see what you're saying, i didn't know you were using degrees. depending on the size of your areas you might not get the smallest right square my way anyway with degrees. @BERA true if you don't keep it right wich i'm assuming his rectangles are (ie polygons['geometry'].envelope returns a bounding box) Commented Sep 23, 2020 at 13:53

I ended up creating the following function

from shapely.geometry import Point
from math import sqrt

def to_square(polygon):

minx, miny, maxx, maxy = polygon.bounds

# get the centroid
centroid = [(maxx+minx)/2, (maxy+miny)/2]
# get the diagonal
diagonal = sqrt((maxx-minx)**2+(maxy-miny)**2)

return Point(centroid).buffer(diagonal/sqrt(2.)/2., cap_style=3)


that I can map on my geopandas dataframe

squares = polygons
squares['geometry'] = squares['geometry'].map(to_square)