Created
July 14, 2015 18:28
-
-
Save cindygis/d08802236f05d184c097 to your computer and use it in GitHub Desktop.
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# | |
# @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