gpt4 book ai didi

python - 使用 Python/Shapely 聚合地理点的最佳方式

转载 作者:太空宇宙 更新时间:2023-11-03 13:17:50 25 4
gpt4 key购买 nike

我想将一长串纬度/经度坐标转换为它们所属的美国州(或县)。假设我有状态几何,一种可能的解决方案是针对所有状态检查每个点。

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, 1), (0, 0)]),
Polygon([(0, 0), (1, 0), (1, 1), (0, 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]))

如果仔分割析列表理解,您会发现 list(idx.intersection((point.coords[0]))) 实际上匹配两个多边形的边界框。另外,请注意边界上的点,如 Point(0.5, 0.5) 不会与 within 匹配,但会与 intersects 匹配.因此,请准备好匹配 0 个、1 个或多个多边形。

关于python - 使用 Python/Shapely 聚合地理点的最佳方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23871409/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com