Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/351.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
用Python/Shapely聚合地理点的最佳方法_Python_Shapely - Fatal编程技术网

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

用Python/Shapely聚合地理点的最佳方法,python,shapely,Python,Shapely,我想将一长串lat/long坐标转换为它们所属的美国州(或县)。一个可能的解决方案是,假设我有状态几何,检查每个点与所有状态 for point in points: for state in states: if point.within(state['shape']): print state.name 有没有一种更优化的方法可以做到这一点,可能是在O(1)中?使用空间索引来快速识别零个或多个多边形的边界框中的点,然后使用Shapely来确定

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

for point in points:
    for state in states:
        if point.within(state['shape']):
            print state.name
有没有一种更优化的方法可以做到这一点,可能是在O(1)中?

使用空间索引来快速识别零个或多个多边形的边界框中的点,然后使用Shapely来确定该点所在的多边形

与此示例类似


如果仔细分析列表,您将看到
list(idx.intersection((point.coords[0]))
实际上与两个多边形的边界框相匹配。另外,请注意,边界上的点,如
点(0.5,0.5)
不会与
中的
匹配,但会与
相交的
匹配。因此,请准备好匹配0、1或更多多边形。

Hi,@MikeT。您是否知道如何使用它来优化此问题?非常感谢。
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]))