Thursday 20 October 2016

Merging overlapping features using Geopandas?


I have a Shapefile with overlapping features. Is there an easy way to merge them with geopandas?


I found a way with shapely, but I would like to do it with geopandas directly.



Answer



The GeoDataFrame



import geopandas as gpd
g1 = gpd.GeoDataFrame.from_file("poly_intersect.shp")
g1.shape
(4, 3)

enter image description here


enter image description here


1) You can use the itertools module


a) If you want to merge the intersections of the overlapping polygons


import itertools

geoms = g1['geometry'].tolist()
intersection_iter = gpd.GeoDataFrame(gpd.GeoSeries([poly[0].intersection(poly[1]) for poly in itertools.combinations(geoms, 2) if poly[0].intersects(poly[1])]), columns=['geometry'])
intersection_iter.to_file("intersection_iter.shp")

enter image description here


enter image description here


Union


union_iter = intersection_iter.unary_union

b) If you want to merge the intersected polygons change intersection by union (all the polygons overlap in my example)



enter image description here


2) You can use GeoPandas Overlay


a)


auto_inter = gpd.overlay(g1, g1, how='intersection')
auto_inter.shape
(7,4)

The resulting GeoDataframe


enter image description here


GeoPandas add the intersection geometries to the existing geometries, therefore



intersection = auto_inter[4:7]
intersection.to_file("intersection.shp")

enter image description here


Union


union = intersection.unary_union

b) use gpd.overlay(g1, g1, how='union')


No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...