繁体   English   中英

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

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

我一直在尝试在地理数据框上使用“相交”功能,以查看哪些点位于多边形内。 但是,只有框架中的第一个特征会返回 true。 我究竟做错了什么?

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)

根据文档

二元运算可以在两个 GeoSeries 之间应用,在这种情况下,运算是按元素执行的。 这两个系列将通过匹配索引对齐。

你的例子不应该起作用。 因此,如果要测试每个点是否位于单个多边形中,则必须执行以下操作:

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

您可能还会查看如何处理 Shapely 中的舍入错误,以了解边界上的点可能出现的问题。

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

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)

由于 geopandas 最近经历了许多性能提升的变化,这里的答案已经过时了。 Geopandas 0.8 引入了许多变化,可以更快地处理大型数据集。

import geopandas
from shapely 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')

检查示例: 链接

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM