二元/一元谓词函数将所有对象与 python 中的所有其他对象进行交叉比较

Binary / unary predicate functions cross-comparing ALL objects with ALL other objects in python

我问过 before. Since the arcpy solution is a very cumbersome, I'm now looking for basically the same feature in geopandas. The question is: What is the fastest / best way to apply a binary predicate function (e.g. touches) x 每个 特征与 每个其他 特征的比较x 或不同的数据集 y。我希望输出类似于 R:

中的默认行为

If y is missing, st_predicate(x, x) is effectively called, and a square matrix is returned with diagonal elements st_predicate(x[i], x[i]).

用一些虚拟数据和函数 st_overlaps() 来举例说明:

library(sf)

b0 = st_polygon(list(rbind(c(-1,-1), c(1,-1), c(1,1), c(-1,1), c(-1,-1))))
a0 = b0 * 0.8
a1 = a0 * 0.5 + c(2, 0.7)
a2 = a0 + 1
a3 = b0 * 0.5 + c(2, -0.5)
x = st_sfc(a0,a1,a2,a3)

plot(x)

st_overlaps(x)
#> Sparse geometry binary predicate list of length 4, where the predicate was `overlaps'
#>  1: 3
#>  2: 3
#>  3: 1, 2
#>  4: (empty)

如何在 python / geopandas 中实现类似的行为?显然,geopandas 自动对齐 xx/y 并执行 元素明智的 比较(参见 and this issue on github ).在 python、运行 x.overlaps(x) 中只是 returns 一个具有四个 True 值的 pandas 系列。

import geopandas as gpd

x.overlaps(x)
0      True
1      True
2      True
3      True

这绝对不是最快的方法,因为它只是一个简单的迭代器,但如果您的数据不是很大,它可能会完成工作。

import geopandas as gpd
from shapely.geometry import Polygon

b0 = Polygon([(-1,-1), (1,-1), (1,1), (-1,1)])
a1 = Polygon([(1.5,0.2), (2.5,0.2), (2.5,1.2), (1.5,1.2)])
a2 = Polygon([(0,0), (2,0), (2,2), (0,2)])
a3 = Polygon([(1.5,-1), (2.5,-1), (2.5,-0.2), (1.5,-0.2)])

series = gpd.GeoSeries([b0, a1, a2, a3])

results = {}
for poly in series.iteritems():
    results[poly[0]] = []
    for poly2 in series.drop(poly[0]).iteritems():
        if poly[1].overlaps(poly2[1]):
            results[poly[0]].append(poly2[0])

它会给你口述你的价值观。

{0: [2], 1: [2], 2: [0, 1], 3: []}

但是,请注意它会检查 A->B,然后检查 B->A,并且它还会检查多边形,即使它们显然很远。为了加快速度,您可以使用 rtree 空间索引仅检查那些可能重叠的多边形,而不是检查每个多边形(两次)。

惯用的 Python 表达方式是列表理解,例如要创建由元组组成的列表(索引:(overlapping-indices)),你会写

[ ( ind, 
    [ind2 for ind2, g2 in enumerate(series) if g.overlaps(g2)] 
  ) 
  for ind, g in enumerate(series) ]

结果:

[(0, [2]), (1, [2]), (2, [0, 1]), (3, [])]

但是正如 martinfleis 所指出的那样,这并不是一种非常有效的方法,因为它不使用任何类型的空间索引。

使用叠加操作可能会获得更好的性能,请参阅http://geopandas.org/set_operations.html