Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Sorts a polygon feature class by descending X and ascending Y, to obtain the spatial order of the polys from left to right, top to bottom. Bypasses the Advanced licence needed to do this in the Sort tool.
#
# @date 13/07/2015
# @author Cindy Williams
#
# Sorts a polygon feature class by descending X and ascending Y,
# to obtain the spatial order of the polys from left to right,
# top to bottom. Bypasses the Advanced licence needed to
# do this in the Sort tool.
#
# For use in the Python window in ArcMap.
#
import arcpy
mxd = arcpy.mapping.MapDocument("CURRENT")
lyr = arcpy.mapping.ListLayers(mxd, "DDP")[0]
# Get the extent of each feature, and store as tuple (name, x coord of top right, y coord of top right)
ddp = [(row[0], row[1].extent.XMax, row[1].extent.YMax) for row in arcpy.da.SearchCursor(lyr, ("Name", "SHAPE@"))]
# Sort by x descending
ddp.sort(key=lambda row:row[1], reverse=True)
# Sort by y ascending
ddp.sort(key=lambda row:row[2])
# Reverse the list to get the L->R, T->B order
dct = {}
# Must still be optimised
for i, j in enumerate(reversed(ddp)):
# Key is name, value is index + 1
dct[j[0]] = i + 1
# Write values back to feature class
with arcpy.da.UpdateCursor(lyr, ("Name", "MapNum")) as cursor:
for row in cursor:
row[1] = dct[row[0]]
cursor.updateRow(row)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.