Search code examples
pythonpolygongeopandasmultipolygons

Account for MultiPolygons with geopandas.apply


How do I amend the following python code: that determines the number of sides/edges of a polygon; to account for MultiPolygons? ---interiors aren't necessary. exteriors only please.
Without looping would be appreciated.
Data can be found here

edges = fp.geometry.apply(lambda x: len(x.exterior.coords)) - 1
edges

0    5
1    4
2    4
3    4
Name: geometry, dtype: int64

Solution

  • You can check if the geometry is an instance of MultiPolygon and if so convert the MultiPolygon to a list of Polygons, calculate the number of edges for each, and then sum the total:

    edges = fp.geometry.apply(lambda x: (
        len(x.exterior.coords) - 1
        if not isinstance(x, MultiPolygon) 
        else sum([len(poly.exterior.coords) - 1 for poly in list(x.geoms)])
    ))
    

    You might also consider using shapely.get_num_points and shapely.get_parts so your code is more explicit in what it is doing:

    from shapely import get_num_points, get_parts
    edges = fp.geometry.apply(lambda x: (
        get_num_points(x.exterior) - 1
        if not isinstance(x, MultiPolygon) 
        else sum([get_num_points(poly.exterior) - 1 for poly in get_parts(x)])
    ))