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

2024-04-25 13:13:47 发布

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

我以前问过a very similar question。由于arcpy解决方案非常麻烦,我现在在geopandas中寻找基本相同的特性。问题是:应用二进制谓词函数(e.g. ^{})的最快/最好的方法是什么,其中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,并执行元素比较(参见this SO questionthis issue on github)。在python中,运行x.overlaps(x)只返回一个带有四个True值的pandas序列。你知道吗

import geopandas as gpd

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

Tags: 数据函数truea2isa1特征b0
2条回答

Python的惯用表达方式是使用列表理解,例如,要创建由元组(index:(overlapping index))组成的列表,您可以编写

[ ( 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

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

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空间索引只检查那些可能重叠的多边形,而不是检查每个多边形(两次)。你知道吗

相关问题 更多 >