基于最近多边形顶点填充点场

2024-10-02 12:29:12 发布

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

我需要根据最近的多边形Name字段填充点Name字段。我尝试使用arcpy.analysis.GenerateNearTable创建内存中的表,但它没有保存我需要的任何字段。如何才能做到这一点并避免创建新层和删除连接

near_result = arcpy.analysis.GenerateNearTable(
       fc, 
       fc1, 
       r'in_memory\neartable', 
       '', 
       'LOCATION', 
       'NO_ANGLE', 
       'CLOSEST')

rows = arcpy.SearchCursor(near_result)
for row in rows:
    arcpy.CalculateField_management(fc, "Name", "Name", "PYTHON_9.3", "")

我也尝试过这个更新光标,但它只在点位于多边形中时起作用

with arcpy.da.UpdateCursor(fc, ['SHAPE@','Name']) as ucursor:
    for update_row in ucursor:
        with arcpy.da.SearchCursor(fc1, ['SHAPE@', 'Name']) as scursor:
            for search_row in scursor:
                if update_row[0].within(search_row[0]):
                    update_row[1] = search_row[1]
                    ucursor.updateRow(update_row)

Tags: nameinforsearchupdateanalysisresult多边形
1条回答
网友
1楼 · 发布于 2024-10-02 12:29:12

我不想这么说,但最好是进行空间连接,但可以在内存中创建要素类,然后立即将其删除。以下是我在类似情况下的做法:

target_fc = 'Points'
join_fc = 'Polygons'
target_fld = 'Name'
join_fld = 'Name'
search_radius = '100 feet'

sj = 'memory\\temp_sj'
if arcpy.Exists(sj):
    arcpy.management.Delete(sj)

arcpy.analysis.SpatialJoin(target_fc, join_fc, sj, 'JOIN_ONE_TO_ONE',
                           'KEEP_COMMON', None, 'CLOSEST', search_radius)

# Create dictionary with key=point object id, val=nearest polygon name
# Note, TARGET_FID is always the field for OBJECTID of target feature
#     prior to the spatial join
# I sometimes like to do a dry run in Pro to make sure the field I want
#     is actually called "Polygons.Name" and the spatial join is doing the right thing
point_dict = {}
with arcpy.da.SearchCursor(sj,['TARGET_FID', f'{join_fc}.{join_fld}']) as cursor:
    for row in cursor:
        oid = row[0]
        polygon_name = row[1]
        point_dict[oid] = polygon_name

arcpy.management.Delete(sj)  # Delete temp spatial join feature class

# only update features that had a polygon within the search radius
# technically the WHERE clause is redundant bc we specified "KEEP_COMMON"
#     in the spatial join.
sql_where = f"OBJECTID IN {str(tuple(point_dict))}"
with arcpy.da.UpdateCursor(target_fc,['OBJECTID',target_fld],sql_where) as cursor:
    for row in cursor:
        oid = row[0]
        row[1] = point_dict[oid]  # Polygon name
        cursor.updateRow(row)

如果您的数据集有多条记录,那么这将比使用嵌套游标快得多

相关问题 更多 >

    热门问题