从非重叠点和多边形获取属性

2024-05-17 13:44:32 发布

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

我有两个地理数据集——一个是点(来自不同多边形的质心,我们将其命名为点_数据),另一个是整个国家的多边形(我们将其命名为多边形_数据)。我现在要做的是从多边形数据中获取属性,并将它们放入点数据中。但问题是它们之间没有重叠

为了更好地理解上下文,该国本质上是群岛,而这些点位于该国之外(这就是它们不重叠的原因)

我尝试过的一些解决方案有:

1.)缓冲多边形_数据,使其接触点_数据。不幸的是,这造成了问题,因为不在海岸线上的形状也被缓冲了

2.)使用了点_数据的原始多边形并进行了spatial join(相交),但问题是有些点仍然返回null值,并且也出现了重复行

我想让这个过程尽可能无缝和简单。有什么想法吗

我对geopandas和qgis都很精通,但我更喜欢geopandas

感谢能够提供帮助的人。:)


Tags: 数据属性原因国家解决方案多边形地理命名
1条回答
网友
1楼 · 发布于 2024-05-17 13:44:32

我想您可以根据点和多边形之间的距离尝试连接数据。通过这样做,可以为每个点获取最近多边形特征的索引,然后使用此索引进行连接

为了复制您的问题,我生成了一层点和一层多边形(它们有一个属性name,我想放在点层上)

enter image description here

一种(天真的)方法可以是:

# read the polygon layer and the point layer
poly_data = gpd.read_file('poly_data.geojson')
pt_data = gpd.read_file('pt_data.geojson')

# Create the field to store the index
# of the nearest polygon feature
pt_data['join_field'] = 0

for idx, geom in pt_data['geometry'].iteritems():
    # Compute the distance between this point and each polygon
    distances = [
        (idx_to_join, geom.distance(geom_poly))
        for idx_to_join, geom_poly in poly_data['geometry'].iteritems()]
    # Sort the distances...
    distances.sort(key=lambda d: d[1])
    # ... and store the index of the nearest polygon feature
    pt_data.loc[(idx, 'join_field')] = distances[0][0]


# make the join between pt_data and poly_data (except its geometry column)
# based on the value of 'join_field'
result = pt_data.join(
        poly_data[poly_data.columns.difference(['geometry'])],
        on='join_field')

# remove the `join_field` if needed
result.drop('join_field', axis=1, inplace=True)

结果:name列中的值来自多边形)

    id                  geometry name
0    1  POINT (-0.07109 0.40284)    A
1    2   POINT (0.04739 0.49763)    A
2    3   POINT (0.05450 0.29858)    A
3    4   POINT (0.06635 0.11848)    A
4    5   POINT (0.63744 0.73934)    B
5    6   POINT (0.61611 0.53555)    B
6    7   POINT (0.76540 0.44787)    B
7    8   POINT (0.84597 0.36256)    B
8    9  POINT (0.67062 -0.36493)    C
9   10  POINT (0.54028 -0.37204)    C
10  11  POINT (0.69194 -0.60900)    C
11  12  POINT (0.62085 -0.65166)    C
12  13  POINT (0.31043 -0.48578)    C
13  14  POINT (0.36967 -0.81280)    C

根据数据集的大小,您可能需要考虑更有效的方法(例如,定义每个点周围的最大搜索半径,以避免必须遍历所有多边形)。p>

相关问题 更多 >