7

I'm writing code that loads data into a database. I have to do some validation/clean up of the data before inserting it. One of the requirements of the database is that this particular table only accepts multipolygons. (It's simpler to just make everything consistently a multipolygon than to try to handle the two different cases.)

I have the shape in the form of a Polygon object. I need to convert it to a multipolygon for insertion. (I would just use the SQL methods for this, but unfortunately, I'm using an ORM right now.)

How can I convert the Polygon object into a MultiPolygon object?

11

You can wrap the polygon in a list and pass that as an argument to the MultiPolygon constructor.

Demo:

from shapely.geometry.multipolygon import MultiPolygon
from shapely import wkt

p = wkt.loads(u'POLYGON((0 0,0 1,1 1,0 0))')
m = MultiPolygon([p])
print(m.wkt)
# prints 'MULTIPOLYGON (((0 0, 0 1, 1 1, 0 0)))'

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.