1

I have two shapefiles:

  • First one is polygons;
  • Second is grid file which divides the territory in equal squares. Each grid cell has its corresponding number.

I need to get the shapefile of grid cells which overlays with the polygons. If I use gpd.overlay(df1,df2,how='intersection') I get back the polygon file, however I am interested in grid cells.

This is how it looks: enter image description here

And the result would be something like this (the red line). A shapefile with corresponding grid cells which overlays and the numbers. enter image description here

I tried to do this with multiple approaches. With the first one I got an error of:

pandas.core.indexing.IndexingError: Unalignable boolean Series provided as indexer (index of the boolean Series and of the indexed object do not match)

and with the rest using GeoPandas overaly, I got back the polygon file not the grid file. This probably is very simple, however I could not figure it out.

import geopandas as gpd

polygons = gpd.read_file(r'E:\...\polygons.shp')
grid = gpd.read_file(r'E:\...\grid.shp')

# set crs
polygons, grid = polygons.set_crs(crs), grid.set_crs(crs)
print(polygons.crs, grid.crs)

# ver1
new_df1 = grid.loc[polygons.intersects(grid.unary_union)].reset_index(drop=True)
# pandas.core.indexing.IndexingError: Unalignable boolean Series provided as indexer (index of the boolean Series and of the indexed object do not match).

# ver2
res_difference = gpd.overlay(grid, polygons, how='intersection')
print(res_difference)

# ver3
res_difference = gpd.overlay(polygons, grid, how='intersection')
print(res_difference)

# ver4 
polyInGrid = gpd.sjoin(polygons, grid, op='within')

1 Answer 1

1

Use Spatial Join.

inner will keep only the grids which overlap polygons

[['geometry']] is to select only the polygon geometry column, otherwise you would get all attributes from the polygons in the result.

import geopandas as gpd

grid = gpd.read_file(r'C:\GIS\data\tempdata\grid.shp')
polygons = gpd.read_file(r'C:\GIS\data\tempdata\my.shp')

grids_with_polygons = gpd.sjoin(left_df=grid, right_df=polygons[['geometry']], how='inner')

enter image description here

Your Answer

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

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