4

Given a dataframe, is it possible to find polygons that lie within another polygon in the same dataframe and remove them based on a condition?

For example, consider the following dataframe

                                            geometry          category            
0  POLYGON ((332294.432 2794730.319, 332294.032 2...            A                
1  POLYGON ((332193.232 2794730.719, 332192.832 2...            B                
2  POLYGON ((332271.632 2794731.519, 332271.232 2...            C                
3  POLYGON ((332271.632 2794731.519, 332271.232 2...            C          

Suppose polygon 3 lies within polygon 2. Since they are both of category C, I would like to remove polygon 3. If they were of different categories, I would not do a removal.

Is there a way to do this within geopandas?

1 Answer 1

2

enter image description here

import geopandas as gpd
from itertools import permutations

df = gpd.read_file(r'/home/bera/Desktop/within.shp')
category_field = 'cat'

indices = df.index.to_list()

to_delete = []
for p1, p2 in permutations(indices,2): #https://stackoverflow.com/questions/104420/how-to-generate-all-permutations-of-a-list
    #print(p1, p2)
    if df.iloc[p1][category_field] == df.iloc[p2][category_field] and df.iloc[p1].geometry.within(df.iloc[p2].geometry):
        to_delete.append(p1)

#>>to_delete
#>>Out[18]: [1]

if len(to_delete)>0:
    df = df.drop(df.index[to_delete])
4
  • Can you please tell how did you access GeoPandas in QGIS?
    – Taras
    Commented Aug 23, 2020 at 14:12
  • I didnt. I did the coding in Anaconda and just displayed the polygons in QGIS
    – Bera
    Commented Aug 23, 2020 at 14:14
  • 1
    Thank you, I know that it is possible, but still can not achieve that ...
    – Taras
    Commented Aug 23, 2020 at 14:15
  • This seems like it could be extremely slow with a layer containing many features as the formula for permutations is P(n,r) = n! / (n-r)!. Maybe an intermediate step could be used to reduce n by comparing the distances from centroids to nearest neighboring centroids and filtering them with some threshold value.
    – Kartograaf
    Commented Sep 15, 2022 at 20:54

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.