最近看到群里有小伙伴有这样的需求,大概意思是这样的。他有一个面数据,这么面数据有很多条记录(polygon),我们姑且把这个面叫A数据,还有另外一个B数据,也是有很多条记录(polygon)。现在需要A数据中每一条记录与B面求交,然后找出所有的相交面,在这些相交面中取面积最大者的一些属性填到A面的那条记录的属性表中,基本上流程就走完了。不知道我需求说明讲得清楚么。
好了,下面我把数据拿上来。A数据为下图的impBase.shp矢量数据。其中的DLMC为空数据,这个字段我们需要在B数据中拿过来。
而B数据,则为另外一个矢量面数据。有DLMC字段,现在需要将该字段经过上面的逻辑后取出来,用于填到上面A数据的DLMC字段。
我们来看一下实现代码。在这个例子中,我们将会使用属性表的遍历,在内存中创建要素类对象,添加字段,添加属性值,更新插入属性表。空间分析中的求交,游标遍历,令牌的使用,还有内存里数据的删除。花了一点时间调出来的。大家可以试着自己写一下。具体的逻辑可以参考我写的代码。
import arcpy
imptAttrPath="D:/QQGroups/shp_inserct/impAtt.shp"
imptBasePath="D:/QQGroups/shp_inserct/impBase.shp"
arcpy.env.overwriteOutput = True
outputSR = arcpy.Describe(imptBasePath).spatialReference
with arcpy.da.UpdateCursor(imptBasePath, ['FID','SHAPE@','DLMC']) as updateCursor:
for updateRow in updateCursor:
#createFC = "in_memory/"+str(updateRow[0])
createFC = r"in_memory\tempUpdate"
arcpy.CreateFeatureclass_management(
"in_memory",
"tempUpdate",
"POLYGON", "", "", "",
outputSR)
arcpy.AddField_management(createFC, "TDYT", "TEXT")
cur = arcpy.InsertCursor(createFC)
newRow = cur.newRow()
newRow.shape = updateRow[1]
newRow.TDYT=updateRow[2]
cur.insertRow(newRow)
arcpy.Intersect_analysis([createFC,imptAttrPath],
out_feature_class="in_memory/IntersectShapeFile",
join_attributes="ALL", cluster_tolerance="#", output_type="INPUT")
area=0.0
dlmc=""
with arcpy.da.SearchCursor("in_memory/IntersectShapeFile", ["Flag", "SHAPE@AREA", "DLMC"]) as maxCursor:
for maxRow in maxCursor:
tmpArea=maxRow[1]
if area<=tmpArea:
area=tmpArea
dlmc=maxRow[2]
updateRow[2]=dlmc
updateCursor.updateRow(updateRow)
#arcpy.Delete_management(["in_memory/"+str(updateRow[0]),"in_memory/IntersectShapeFile"])
arcpy.Delete_management('in_memory')
print "finished"
在写代码的时候,特别要注意游标遍历方法的应用,字段在游标中是否存在。相交计算中需要注意设置要输出类型,有"LINE","INPUT",具体可以参考ArcGIS Desktop里面的相交工具中参数。还有内存的删除,使用数组的方式一一删除内存中的数据,可能会出现错误,至少我是没有试成功。
最后,将实现得到这样的结果。
更多内容,请微信扫二维码关注公众号,或者加入arcpy开发qq学习群:487352121