[GIS] Converting list of polygons to multipolygon using shapely

polygonpythonshapely

I have a list of polygons where each polygon is a wkt form as follows:

list_polygons =  ['POLYGON ((-88.131229288 41.900200029,-88.12973798 41.900104202,-88.129785999 41.894907769,-88.131352409 41.895051521,-88.131229288 41.900200029))', 'POLYGON ((-88.121359263 41.887694051,-88.12027565 41.887654116,-88.120264921 41.884451192,-88.11968556399999 41.884483142,-88.11962119099999 41.882669946,-88.121251974 41.882637995,-88.121359263 41.887694051))']

I want to convert into a multi polygon wkt as ['MULTIPOLYGON ((-88.131229288 41.900200029,-88.12973798 41.900104202,-88.129785999 41.894907769,-88.131352409 41.895051521,-88.131229288 41.900200029))', 'POLYGON ((-88.121359263 41.887694051,-88.12027565 41.887654116,-88.120264921 41.884451192,-88.11968556399999 41.884483142,-88.11962119099999 41.882669946,-88.121251974 41.882637995,-88.121359263 41.887694051))']

I tried the following but gives me assertion error:

from shapely.geometry.multipolygon import MultiPolygon
Multipolygon(list_polygons)

I also tried to debug like this

p = wkt.loads('POLYGON ((-88.131229288 41.900200029,-88.12973798 41.900104202,-88.129785999 41.894907769,-88.131352409 41.895051521,-88.131229288 41.900200
029))')
*** SyntaxError: SyntaxError('invalid syntax', ('<string>', 1, 1, "= wkt.loads('POLYGON ((-88.131229288 41.900200029,-88.12973798 41.900104202,-88.129785999 41.894907769,-88.131352409 41.895051521,-88.131229288 41.900200029))')"))

What is it that I am doing wrong?

Best Answer

This works for me under shapely '1.6.4.post1':

import shapely.wkt
import shapely.geometry

list_wkt = ['POLYGON ((-88.131229288 41.900200029,-88.12973798 41.900104202,-88.129785999 41.894907769,-88.131352409 41.895051521,-88.131229288 41.900200029))', 'POLYGON ((-88.121359263 41.887694051,-88.12027565 41.887654116,-88.120264921 41.884451192,-88.11968556399999 41.884483142,-88.11962119099999 41.882669946,-88.121251974 41.882637995,-88.121359263 41.887694051))']

list_polygons =  [shapely.wkt.loads(poly) for poly in list_wkt]

print( shapely.geometry.MultiPolygon(list_polygons) )

Resulting in:

MULTIPOLYGON (((-88.131229288 41.900200029, -88.12973798 41.900104202, -88.12978599900001 41.894907769, -88.131352409 41.895051521, -88.131229288 41.900200029)), ((-88.121359263 41.887694051, -88.12027565 41.887654116, -88.120264921 41.884451192, -88.11968556399999 41.884483142, -88.11962119099999 41.882669946, -88.121251974 41.882637995, -88.121359263 41.887694051)))

This is difficult to say what is not working for you as you don't provide full code but your last line works in my system:

p = shapely.wkt.loads('POLYGON ((-88.131229288 41.900200029,-88.12973798 41.900104202,-88.129785999 41.894907769,-88.131352409 41.895051521,-88.131229288 41.900200029))')