4
votes

My python3 script created the variable geometries_list whose value is a list of shapefiles, each a polygon representing a geographic area

[<shapefile.Shape at 0x7f060abfae48>,
 <shapefile.Shape at 0x7f05dcaf1cc0>,
 <shapefile.Shape at 0x7f060a86b278>,
 <shapefile.Shape at 0x7f05da470668>]

I want to "merge" the polygons. I tried the following code

from functools import reduce
from shapely.geometry import Polygon
union = reduce(lambda x,y: x.union(y), geometries_list) 

but it gives the result: AttributeError: 'Shape' object has no attribute 'union'

I see another method which involves creating a shapefilewriter object and successively overwriting each polygon on the list https://gis.stackexchange.com/questions/103033/using-pyshp-to-merge-two-shapefiles This approach might work, but each overwrite is saved to disk

1
the following resolved the issue geometries_list = [geometry.Polygon(x.points) for x in geometries_list]rightsized

1 Answers

3
votes

Perhaps worth mentioning that shapely.ops.unary_union is a more effective method for merging shapes.

You can convert the shapefile.Shape objects to shapely.Polygon objects through their GeoJSON representation and merge them as follows.

from shapely.geometry import shape
from shapely.geometry.ops import unary_union

union = unary_union([shape(s.__geo_interface__) for s in geometries_list])