如何解决根据最近的多边形 acrpy 填充点字段
我需要根据最近的多边形 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","PYTHON_9.3","")
我也试过这个更新光标,但它只在点在多边形中时才有效。
with arcpy.da.UpdateCursor(fc,['SHAPE@','Name']) as ucursor:
for update_row in ucursor:
with arcpy.da.SearchCursor(fc1,'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)
解决方法
我不想这么说,但您最好进行空间连接,但您可以在内存中创建要素类,然后立即将其删除。以下是我在类似情况下所做的:
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)
如果您的数据集有多个记录,这将比使用嵌套游标快得多。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。