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.
Geographic Information Systems Stack Exchange is a question and answer site for cartographers, geographers and GIS professionals. It only takes a minute to sign up.
Sign up to join this communityI 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.
The GeoDataFrame
import geopandas as gpd
g1 = gpd.GeoDataFrame.from_file("poly_intersect.shp")
g1.shape
(4, 3)
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")
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)
2) You can use GeoPandas Overlay
a)
auto_inter = gpd.overlay(g1, g1, how='intersection')
auto_inter.shape
(7,4)
The resulting GeoDataframe
GeoPandas add the intersection geometries to the existing geometries, therefore
intersection = auto_inter[4:7]
intersection.to_file("intersection.shp")
Union
union = intersection.unary_union
b) use gpd.overlay(g1, g1, how='union')
If you want to output a layer of distinct merged overlapping polygons, and not just a single multi-polygon, then after using:
union = intersection.unary_union
you can convert the resulting multi-poly to a GeoSeries:
shapes_series = gpd.GeoSeries([polygon for polygon in union])
or to a GeoDataFrame:
shapes_df = gpd.GeoDataFrame([polygon for polygon in union]).set_geometry(0)