加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

用Python / Shapely聚合地理点的最佳方法

发布时间:2020-12-20 11:35:37 所属栏目:Python 来源:网络整理
导读:我想将一长串纬度/经度坐标转换为它们所属的美国州(或县).考虑到我具有状态几何,一种可能的解决方案是针对所有状态检查每个点. for point in points: for state in states: if point.within(state['shape']): print state.name 有没有更优化的方法来做到这一
我想将一长串纬度/经度坐标转换为它们所属的美国州(或县).考虑到我具有状态几何,一种可能的解决方案是针对所有状态检查每个点.

for point in points:
    for state in states:
        if point.within(state['shape']):
            print state.name

有没有更优化的方法来做到这一点,可能在O(1)?

解决方法

使用 Rtree作为空间索引可以非常快速地识别零个或多个多边形的边界框中的点,然后使用Shapely确定该点所在的多边形.

与此示例https://stackoverflow.com/a/14804366/327026类似

from shapely.geometry import Polygon,Point
from rtree import index

# List of non-overlapping polygons
polygons = [
    Polygon([(0,0),(0,1),(1,0)]),Polygon([(0,]

# Populate R-tree index with bounds of polygons
idx = index.Index()
for pos,poly in enumerate(polygons):
    idx.insert(pos,poly.bounds)

# Query a point to see which polygon it is in
# using first Rtree index,then Shapely geometry's within
point = Point(0.5,0.2)
poly_idx = [i for i in idx.intersection((point.coords[0]))
            if point.within(polygons[i])]
for num,idx in enumerate(poly_idx,1):
    print("%d:%d:%s" % (num,idx,polygons[idx]))

如果您剖析列表推导,您将看到该列表(idx.intersection((point.coords [0])))实际上匹配两个多边形的边界框.另外,请注意边界上的点(如点(0.5,0.5))与内部的任何内容都不匹配,但会匹配两者的相交点.所以要准备好匹配0,1个或更多的多边形.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读