Geopandas: use loop to difference each polygon from the one before in geodataframe?

Viewed 94

I have a geodataframe with many polygons. I'd like to automate differencing with a loop, to do this with each preceding and following polygon and add them to a new gdf:

new_gdf = polygon[0:1].overlay(polygon[1:2], how='difference')

I am able to do this one at a time, but I'd like to find a more efficient way, especially when I will (someday) have a lot of polygons.

Would anyone have an idea of how I might do this? I'm trying to use iterrows(), but am failing on the exact syntax.

Thank you in advance.

1 Answers

Instead of overlay() you might be looking for GeoSeries.difference()

Returns a GeoSeries of the points in each aligned geometry that are not in other.

Would be something like this:

from shapely.geometry import Polygon
import geopandas as gpd

# sample polygons
polys = gpd.GeoDataFrame(geometry=[
    Polygon([(0,0), (2,0), (2,2), (0,2)]),
    Polygon([(1,1), (3,1), (3,3), (1,3)]),
    Polygon([(2,2), (4,2), (4,4), (2,4)]),
    Polygon([(3,3), (5,3), (5,5), (3,5)])])

# polys.iloc[:-1] : rows 0 .. 2 (exclude last row as df sizes must match)
# polys.iloc[1:]  : rows 1 .. 3
# align=False : do not aligns GeoSeries based on their indices; 
# order of elements is preserved.
diffs = polys.iloc[:-1].difference(polys.iloc[1:], align=False)

Sample polys GeoDataFrame:

enter image description here

Resulting diffs GeoDataSeries:

enter image description here

Related