GeoPandas Polygon – Removing Polygons That Touch Other Polygon Borders Using GeoPandas

geopandasintersectionpolygon

How to remove polygons which touches other polygon border?

I have a polygon and a single box outline.

I need to get polygons which are outside the box and do not touches box borders and polygons which are inside the box and also do not touches the borders.

I found a way how to get polygon which are outside the box and do not overlay with borders with these Python lines:

import geopandas as gpd
overlay = polygons.loc[~polygons.intersects(box.unary_union)].reset_index(drop=True)
train = gpd.overlay(overlay,box, how='difference')

Looks like this:

enter image description here

However, I could not find a way to get polygons which are inside the box and do not touches the box borders.
With this I got all polygons inside, but could not remove the ones on the border:

overlay_test = polygons.loc[polygons.intersects(box.unary_union)].reset_index(drop=True)

Looks like this:

enter image description here

Best Answer

Use spatial join. Convert the big polygon to a line using boundary method, select the small polygons that does not intersect the line:

import geopandas as gpd

polygons = gpd.read_file(r'C:\GIS\data\tempdata\grid.shp')
box = gpd.read_file(r'C:\GIS\data\tempdata\box.shp')
box['geometry'] = box.geometry.boundary #Convert polygon geometry to line

joined = gpd.sjoin(left_df=polygons, right_df=box[['geometry']], how='left')
joined = joined.loc[joined['index_right'].isnull()] #Find the polygons which does not touch the line, that is where right index is null
joined.to_file(r'C:\GIS\data\tempdata\disjoint.shp')

enter image description here