如何找到哪些点与 geopandas 中的多边形相交?

How to find which points intersect with a polygon in geopandas?

我一直在尝试在地理数据框上使用 "intersects" 功能,以查看哪些点位于多边形内。但是,只有框架中的第一个特征 return 为真。我做错了什么?

from geopandas.geoseries import *

p1 = Point(.5,.5)
p2 = Point(.5,1)
p3 = Point(1,1)

g1 = GeoSeries([p1,p2,p3])
g2 = GeoSeries([p2,p3])

g = GeoSeries([Polygon([(0,0), (0,2), (2,2), (2,0)])])

g1.intersects(g) # Flags the first point as inside, even though all are.
g2.intersects(g) # The second point gets picked up as inside (but not 3rd)

根据 documentation:

Binary operations can be applied between two GeoSeries, in which case the operation is carried out elementwise. The two series will be aligned by matching indices.

您的示例不应该起作用。所以如果你想测试每个点都在一个多边形中,你必须这样做:

poly = GeoSeries(Polygon([(0,0), (0,2), (2,2), (2,0)]))
g1.intersects(poly.ix[0]) 

输出:

    0    True
    1    True
    2    True
    dtype: bool

或者,如果您想测试特定 GeoSeries 中的所有几何图形:

points.intersects(poly.unary_union)

Geopandas 依靠 Shapely 进行几何工作。直接使用它有时很有用(也更容易阅读)。以下代码也像宣传的那样工作:

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)])

for p in [p1, p2, p3]:
    print(poly.intersects(p))

你也可以看看 边界上的点可能出现的问题。

解决此问题的一种方法似乎是获取特定条目(这不适用于我的应用程序,但可能适用于其他人的应用程序:

from geopandas.geoseries import *

p1 = Point(.5,.5)
p2 = Point(.5,1)
p3 = Point(1,1)

points = GeoSeries([p1,p2,p3])

poly = GeoSeries([Polygon([(0,0), (0,2), (2,2), (2,0)])])

points.intersects(poly.ix[0])

另一种方法(对我的应用程序更有用)是与第二层的特征的一元并集相交:

points.intersects(poly.unary_union)

您可以使用下面这个简单的函数轻松检查哪些点位于多边形内:

import geopandas
from shapely.geometry import *

p1 = Point(.5,.5)
p2 = Point(.5,1)
p3 = Point(1,1)

g = Polygon([(0,0), (0,2), (2,2), (2,0)])

def point_inside_shape(point, shape):
    #point of type Point
    #shape of type Polygon
    pnt = geopandas.GeoDataFrame(geometry=[point], index=['A'])
    return(pnt.within(shape).iloc[0])

for p in [p1, p2, p3]:
    print(point_inside_shape(p, g))

由于 geopandas 最近进行了许多性能增强更改,因此此处的答案已过时。 Geopandas 0.8 引入了许多变化,使处理大型数据集的速度更快。

import geopandas
from shapely.geometry import Polygon

p1 = Point(.5,.5)
p2 = Point(.5,1)
p3 = Point(1,1)

points = GeoSeries([p1,p2,p3])

poly = GeoSeries([Polygon([(0,0), (0,2), (2,2), (2,0)])])

geopandas.overlay(points, poly, how='intersection')

我认为最快的方法是使用 geopandas.sjoin

import geopandas as gpd

gpd.sjoin(pts, poly, how='left', op='intersects')

检查示例:link