Getting counts of intersections between geometries

2020-03-25 06:27发布

问题:

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.

回答1:

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.



回答2:

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