primitivist
primitivist

Reputation: 875

Dissolve GeoDataFrame geometries into single-part Polygons

I have the following function which generates a GeoDataFrame containing randomly sized polygons, each of which belong to a class label:

from random import randint, randrange, seed
from geopandas import GeoDataFrame
from shapely.geometry import Point
import matplotlib.pyplot as plt

def dummy_data(size, obj_count_range, obj_size_range, label_count):
    obj_count = randint(*obj_count_range)
    return GeoDataFrame.from_dict({
            'geometry': [Point(
                randrange(0, size[0]),
                randrange(0, size[1]),
            ).buffer(randint(*obj_size_range)) for _ in range(obj_count)],
            'label': [randint(1, label_count) for _ in range(obj_count)]
    })

As an example, I call the function like so:

seed(1000)
gdf = dummy_data((100000, 100000), (0, 100), (1000, 10000), 3)
print(gdf.head())
plt.show()

The example produces the following outputs:

                                            geometry  label
0  POLYGON ((58850.000 87795.000, 58837.365 87537...      1
1  POLYGON ((53622.000 46264.000, 53612.220 46064...      1
2  POLYGON ((71089.000 21726.000, 71042.003 20769...      3
3  POLYGON ((61974.000 17080.000, 61951.686 16625...      1
4  POLYGON ((94948.000 31549.000, 94914.452 30866...      1

enter image description here

I would like to dissolve intersecting geometries with likewise class labels. Doing gdf.dissolve(by='label') seems to return one MultiPolygon for each class:

label                                           geometry        
1      MULTIPOLYGON (((44788.241 671.703, 44692.635 5...
2      MULTIPOLYGON (((40604.141 5433.140, 40517.465 ...
3      MULTIPOLYGON (((42023.954 13845.668, 41757.317...

My expectation is that it produces a new GeoDataFrame which contains the same single-part geometries as the original, but ones with intersecting likewise classes are unionized into a new Polygon (not MultiPolygon) object. How would I go about doing this?

Upvotes: 1

Views: 1201

Answers (1)

martinfleis
martinfleis

Reputation: 7804

You can get individual parts of resulting MultiPolygons via explode().

singlepart = gdf.dissolve(by='label').explode()

Upvotes: 1

Related Questions