最近看到羣裏有小夥伴有這樣的需求,大概意思是這樣的。他有一個面數據,這麼面數據有很多條記錄(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