9

I have a list of shapely polygons

myList = [[<shapely.geometry.polygon.Polygon object at 0x110e09d90>], [<shapely.geometry.polygon.Polygon object at 0x110e09f90>], [<shapely.geometry.polygon.Polygon object at 0x110ec9150>]]

How would I create a MultiPolygon out of them? I cannot get my head around it

four-eyes
  • 10,740
  • 29
  • 111
  • 220
  • Your list contains several single-element lists containing one polygon each. Your question suggests that you expect a list of polygons instead. – Sven Marnach Apr 21 '16 at 15:33
  • @Pythonista cascaded_union creates a Polygon from a Polygon list (like I posted here?) – four-eyes Apr 21 '16 at 15:33
  • 2
    Here's an example of `cascaded_union` usage. Easier to just look at the code and see if it's what you need http://deparkes.co.uk/2015/02/28/how-to-merge-polygons-in-python/ – Pythonista Apr 21 '16 at 15:35
  • 1
    @Pythonista awesome, thanks! Working for the first time with shapely, pretty hard to keep track of what there is! – four-eyes Apr 21 '16 at 15:38

1 Answers1

13

It looks like you have a list of lists (each with one item). Before you do anything, make a flat list of geometries:

myGeomList = [x[0] for x in myList]

There are actually a few options to combine them. The best is to do a unary union on a list of geometries, which may result in different geometry types, such as MultiPolygon, but it not always.

from shapely.ops import unary_union
cu = unary_union(myGeomList)

Or you could pass the list to MultiPolgyon() or GeometryCollection(), but these might present issues (invalid, inability to use overlay ops, etc.)

Mike T
  • 41,085
  • 18
  • 152
  • 203
  • 2
    Great Answer! Taking directly MultiPolgyon() does not throw errors but results in faulty results. Tested when combining polygons and multipolygons to new multipolygons. – Philipp Schwarz Jun 16 '16 at 18:59
  • 1
    If you have a big data set, perhaps a few gigabytes, this can be really inefficient as `unary_union` will try to merge polygons which share edges – for example, if your polygons represent European countries, it will merge mainland Europe into a single polygon. Identifying shared paths is computationally expensive, and if you don't need this and have a big data set, there must be a better solution. I'm not quite sure what that might be, though. – Richard Smith Jan 03 '21 at 23:55