9

Given a Shapely MultiPolygon, how can I extract the biggest Polygon?

For example, given a MultiPolygon as follows:

from shapely.geometry import Polygon, MultiPolygon

multipolygon = MultiPolygon([Polygon([(0,0), (1,0), (1,0.25), (1, 0.5), (1,0.75), (1,1), (0,1)]),
                             Polygon([(2,0), (1.2,0.25), (1.2,0.25), (1.2,0.75), (2,0.75)])])

enter image description here

How can I get just the largest part?

enter image description here

3 Answers 3

14

Here's what I would do:

max(multipolygon, key=lambda a: a.area)

The built-in max function used this way will return the item from the list where lambda a: a.area is maximized.

1
  • That's really elegant. Love these one-liners!
    – Henrik
    Jun 19, 2020 at 19:40
2

I think I found an interim solution, if there is a better way please let me know!

def get_biggest_part(multipolygon):

    # Get the area of all mutipolygon parts
    areas = [i.area for i in multipolygon]

    # Get the area of the largest part
    max_area = areas.index(max(areas))    

    # Return the index of the largest area
    return multipolygon[max_area]
1
1

As of shapely 2.0.2 (and may be earlier versions), you need to append .geoms:

max(multipolygon.geoms, key=lambda a: a.area)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.