Spatial Digger
Spatial Digger

Reputation: 1993

Geopandas: Converting single polygons to multipolygon, keeping individual polygonal topology?

I assume this is possible. Example: I have polygons in a geodataframe, some polygons have the same attribute data, they are just separate individual polygons with the same data, each polygon has its own row in the gdf.

I would like to combine the polygons into a multipolygon so they take up only 1 row in the gdf. The two polygons overlap, I do not want to dissolve them together, I want them to remain 2 separate entities.

There are single polygons, I assume they will also have to be converted to multipolygons even though they are in the singular as ultimately they will be exported for use in GIS software, one geom type per dataset.

I have achieved a .dissolve(by='ID') but as stated above, I do not want to change the polygons geometry.

Suggestions?

Upvotes: 1

Views: 5341

Answers (1)

martinfleis
martinfleis

Reputation: 7804

You can adapt geopandas' dissolve to generate MultiPolygon instead of unary union. The original code I adapted is here.

import geopandas as gpd
from shapely.geometry import Polygon, MultiPolygon


def groupby_multipoly(df, by, aggfunc="first"):
    data = df.drop(labels=df.geometry.name, axis=1)
    aggregated_data = data.groupby(by=by).agg(aggfunc)

    # Process spatial component
    def merge_geometries(block):
        return MultiPolygon(block.values)

    g = df.groupby(by=by, group_keys=False)[df.geometry.name].agg(
        merge_geometries
    )

    # Aggregate
    aggregated_geometry = gpd.GeoDataFrame(g, geometry=df.geometry.name, crs=df.crs)
    # Recombine
    aggregated = aggregated_geometry.join(aggregated_data)
    return aggregated
df = gpd.GeoDataFrame(
    {"a": [0, 0, 1], "b": [1, 2, 3]},
    geometry=[
        Polygon([(0, 0), (1, 0), (1, 1)]),
        Polygon([(1, 0), (1, 0), (1, 1)]),
        Polygon([(0, 2), (1, 0), (1, 1)]),
    ],
)

grouped = groupby_multipoly(df, by='a')
grouped
                                            geometry  b
a                                                       
0  MULTIPOLYGON (((0.00000 0.00000, 1.00000 0.000...  1
1  MULTIPOLYGON (((0.00000 2.00000, 1.00000 0.000...  3

If you change MultiPolygon within merge_geometries to GeometryCollection, you should be able to combine any type of geometry to a single row. But that might not be supported by certain file formats.

Upvotes: 4

Related Questions