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

2024-09-29 23:20:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我一直在尝试使用geodataframe上的“intersects”功能,查看哪些点位于多边形内。但是,只有帧中的第一个特征将返回为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)

Tags: 功能as特征多边形pointp2insidep3
3条回答

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

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

根据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

或者如果要测试特定地理系列中的所有几何图形:

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

你也可以看看 How to deal with rounding errors in 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)

相关问题 更多 >

    热门问题