Using this example GeoSeries:
s = geopandas.GeoSeries([Polygon([(0, 0), (0, 2), (2, 2), (2, 0)]), Polygon([(0, 1), (0, 3), (2, 3), (2, 1)]),Polygon([(1, 0), (1, 2), (3, 2), (3, 0)]), Polygon([(4, 4), (4, 6), (6, 6), (6, 4)])])
s.plot(alpha=0.5, cmap='Set1')
We could create a matrix indicating which geometries are overlapping:
In [55]: overlap_matrix = s.apply(lambda x: s.overlaps(x)).values.astype(int)
In [56]: overlap_matrix
Out[56]:
array([[0, 1, 1, 0],
[1, 0, 1, 0],
[1, 1, 0, 0],
[0, 0, 0, 0]])
And from that get the groups using scipy's connected components:
In [57]: from scipy.sparse.csgraph import connected_components
In [58]: connected_components(overlap_matrix)
Out[58]: (2, array([0, 0, 0, 1], dtype=int32))
In [59]: n, ids = connected_components(overlap_matrix)
And use dissolve
based on those groups:
In [60]: df = geopandas.GeoDataFrame({'geometry': s, 'group': ids})
In [61]: res = df.dissolve(by='group')
In [62]: res
Out[62]:
geometry
group
0 POLYGON ((0 0, 0 1, 0 2, 0 3, 2 3, 2 2, 3 2, 3...
1 POLYGON ((4 4, 4 6, 6 6, 6 4, 4 4))
In [63]: res.plot(cmap='Set1')
But note: I am certainly not sure if creating such a matrix is the most efficient way.
Further note, this would actually be a nice enhancement to geopandas to enable this somehow (or at least to have a good solution in the examples)