1

I would like to perform in Python, the action done by the following QGIS command:

Processing Toolbox > Vector Geometry > Keep N Biggest Parts

It removes the smallest polygons from a multipolygons shapefile.

So far, I could just do in the following way (N=100):

#Read file
gdf = gpd.read_file('myfile.shp')
#explode and create area column
gdf_ex = gdf.explode()
gdf_ex['area'] = gdf_ex['geometry'].area
#filter biggest 100 areas
gdf_ex = gdf.sort_values('area', ascending=False)[:100]
#dissolve
gdf_simplified = gdf_ex.dissolve(by='CODE')

It works, but I suspect there might be a more direct way

0

1 Answer 1

3

Your code will not consider each polygon/multipolygon on its own. So small singlepart polygons will be dropped if there are other multipolygons parts that are larger.

Try groupby:

import geopandas as gpd
n = 2 #Parts to keep if the geometry is a multipolygon
df = gpd.read_file(r"/home/bera/Desktop/gistest/multi.shp")
df["tempid"] = range(df.shape[0]) #Create a temporary id to group and dissolve by
df = df.explode(index_parts=True) #Explode so each polygon part become one row
df["singlepartarea"] = df.area #Calculate area 
df = df.sort_values(by="singlepartarea", ascending=False) #Sort from largest to smallest area
df2 = df.groupby("tempid").head(n) #For each tempid, keep the top n parts
df2 = df2.dissolve(by="tempid") #Dissolve back to multipolygons
df2.to_file(r"/home/bera/Desktop/gistest/multi_n2.shp")

multi is the start layer, multi_n2 is the result of the code above, keep n biggest parts is the result of QGIS tool:

With your code, the small FID=1 singlepart polygon will be dropped: enter image description here

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.