Search code examples
pythongisspatialshapefilegeopandas

Combining shapefiles in Python / GeoPandas


I have three polygon shapefiles which overlap each other. Let's call them:

  • file_one.shp (polygon Name is 1)
  • file_two.shp (polygon Name is 2)
  • file_three.shp (polygon Name is 3)

I want to combine them and keep the values like this.

enter image description here

How can I achieve the result (As shown in the figure) in Python, please?

Thanks!


Solution

  • First, let's generate some data for demonstration:

    import geopandas as gpd
    from shapely.geometry import Point
    shp1 = gpd.GeoDataFrame({'geometry': [Point(1, 1).buffer(3)], 'name': ['Shape 1']})
    shp2 = gpd.GeoDataFrame({'geometry': [Point(1, 1).buffer(2)], 'name': ['Shape 2']})
    shp3 = gpd.GeoDataFrame({'geometry': [Point(1, 1).buffer(1)], 'name': ['Shape 3']})
    

    Now take the symmetric difference for all, but the smallest shape, that can be left as is:

    diffs = []
    gdfs = [shp1, shp2, shp3]
    for idx, gdf in enumerate(gdfs):
        if idx < 2:
            diffs.append(gdf.symmetric_difference(gdfs[idx+1]).iloc[0])
    diffs.append(shp3.iloc[0].geometry)
    

    There you go, now you have the desired shapes as a list in diffs. If you would like to combine them to one GeoDataFrame, just do as follows:

    all_shapes = gpd.GeoDataFrame(geometry=diffs)