Geographic Information Systems Asked by Pierce_h on March 13, 2021
I am debugging a code provided to me that merges two polygons and alters the fields of “FID1′ and “CALC_AREA.”
I have realized that the current code searches every layer in the map document for fields containing “FID1” & “CALC_AREA”, sorts them ascendingly, chooses the ID matching the largest “CALC_AREA” selected, and assigns the value to all IDs of merged polygons.
def populateMergeID():
mxd = arcpy.mapping.MapDocument("Current")
df = arcpy.mapping.ListDataFrames(mxd)[0]
for lyr in arcpy.mapping.ListLayers(mxd):
# Describe cursor object for selected polygons sorted by area
search = arcpy.SearchCursor(lyr, fields="FID1; CALC_AREA", sort_fields="CALC_AREA A")
FID1 = ""
area = 0
for row in search:
print "Current FID1!: "
print row.FID1
# Just want the first row FID1 value
if row.CALC_AREA > area:
area = row.CALC_AREA
FID1 = row.FID1
# Corresponds to largest polygon in selection
print "The container polygon has FID1 value!!: " + FID1
del search
with arcpy.da.UpdateCursor(lyr,"mergeid") as cursor:
for row in cursor:
row[0] = FID1
cursor.updateRow(row)
print row
# del cursor
My question is that how would I write the script so that the search only looks for selected polygons instead of every polygon in the the map document.
The arcpy search cursor has an optional SQL query that should be used to limit the rows returned instead of selecting by attribute. To my knowledge the arcpy search cursors will not honor existing selections. So if no SQL query is provided to the search cursor parameter you are searching through the entire table. The documentation can be found here.
So your code for example could look something like this:
search = arcpy.SearchCursor(lyr, where_clause='CALC_AREA > 250', fields="FID1; CALC_AREA", sort_fields="CALC_AREA A")
Lastly, in your instance the only reason to continue using the arcpy.SearchCursor
vs. the arcpy.da.SearchCursor
is for the sorting capabilities, otherwise as stated in the ESRI documentation:
The arcpy.da cursors (arcpy.da.SearchCursor, arcpy.da.UpdateCursor, and arcpy.da.InsertCursor) were introduced with ArcGIS 10.1 to provide significantly faster performance over the previously existing set of cursor functions (arcpy.SearchCursor, arcpy.UpdateCursor, and arcpy.InsertCursor). The original cursors are provided only for continuing backward compatibility.
Answered by F_Kellner on March 13, 2021
Get help from others!
Recent Answers
Recent Questions
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP