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.
And the result would be something like this (the red line). A shapefile with corresponding grid cells which overlays and the numbers.
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')