Is it possible to get counts of intersections between two geometries using GeoPandas objects? That is, I want to count up the number of polygons or line strings in one GeoDataFrame that intersect with each polygon in another GeoDataFrame. I did not see an easy way of doing this while browsing the GeoPandas docs, but wanted to check before moving on to lower-level tools.
-
https://stackoverflow.com/questions/54127731/how-can-i-count-the-number-of-polygons-a-shape-intersects – swatchai Apr 21 '21 at 16:59
3 Answers
You want a spatial join: geopandas.tools.sjoin()
.
There's an example in this Jupyter Notebook — look at the section called Spatial join. This is counting a set of points (midpoints
) into a set of polygons (bins
). Both geometries define a GeoDataFrame
.
At the time of writing, tools.sjoin()
is not in the current release of geopandas
. I couldn't get geopandas.tools
to build in any of their branches, but I fixed it — for me anyway — in my fork. My fix is an open PR.

- 7,614
- 1
- 23
- 36
I don't know about a built-in tool to do this but I'm not an expert. At the same time it's easily done with some pandas magic:
import geopandas as gpd
from shapely.geometry import *
p1 = Point(.5,.5)
p2 = Point(.5,1)
p3 = Point(1,1)
poly = Polygon([(0,0), (0,2), (2,2), (2,0)])
df1 = gpd.GeoSeries([p1,p2,p3])
df2 = gpd.GeoDataFrame([poly,p3], columns=['geometries'])
f = lambda x:np.sum(df1.intersects(x))
df2['geometries'].apply(f)
Should return:
0 3
1 1
Name: geometries, dtype: int64

- 626
- 5
- 15
Lets consider 02 geometries (Points and Polygons) which intersect at least once.
- Spatial join of your layers
You should write something like this : pointsInPolygon = gpd.sjoin(points, polygons, how="inner", op='intersects')
Add a field with 1 as a constant value You should write something like this : pointsInPolygon['const']=1
Group by the field according to the column by which you want to aggregate data You should write something like this : pointsInPolygon.groupby(['field']).sum()
The column [const] will give you the count of intersections between your two geometries.
If you want to see others columns as well, just type something like this : df = pointsInPolygon.groupby('field').agg({'columnA':'first', 'columnB':'first', 'const':'sum'}).reset_index()

- 131
- 5