I am reading a shapefile and I have extracted a specific row from it that is a Multipolygon. I can extract all the polygons in it with .explode() which works great and I get 130+ polygons.

How can I merge the ones that are next to each other?

I know the 130+ resulting polygons represent two islands, and I want to get each as a polygon. I have looked up how to do it but haven't been able to find anything and this is my first project ever using geopandas and shapely.

gdf=gpd.read_file("comunas.shp").to_crs({'init': 'epsg:4326'})
Rapa_Nui=gdf.loc[gdf["Comuna"]=="Isla de Pascua"]
  • The linked shapefile is not readable for me (note that a shapefile always comes as multiple files, you might need to zip them to share) – joris Feb 2 at 19:50
  • Thanks! I changed the link to contain the zip – M.O. Feb 2 at 19:58

You can first union all polygons with unary_union:

single_multi_polygon = all_Rapa_Nui.unary_union

This should now be a single MultiPolygon consisting of two polygons for the two islands. And then you can get the polygon parts of this MultiPolygon:

polygons = single_multi_polygon.geoms
| improve this answer | |
  • That still returns the 167 polygons. – M.O. Feb 2 at 20:50
  • I checked the data, and apart from one big island, there seem to be many small islands, so it seems logical that it still returns many polygons. – joris Feb 2 at 20:56
  • Oh then it's my bad..explode() and your answer lead to the same amount of polygons so I just assumed it wasn't working. I guess I can't see all those tiny polygons on the plots I have been making so I just thought the big pieces of land were a mix of a lot of polygons . – M.O. Feb 2 at 21:10

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.