Tuesday, 10 May 2016

coordinate system - Assigning numbers to grid of polygons using ArcPy?


grid of polygons


I would like to number the shown grid of polygons. The numbers should go left to right top to bottom, starting at 1. I'm using ArcGIS Desktop with a Basic license, and would prefer to do this with ArcPy.



Answer



Your question is a "duplicate" of Sorting grid cells in fishnet grid by location and number using QGIS? but using arcpy:



import arcpy
fc = r'C:\data.gdb\features' #Change
field_to_update = 'somefield' #Change, needs to be added before running the code
decimals = 0 #Rounding. You might need to adjust to get desired output. My coordinates are in meters so I use zero decimals. If your grid is tilted, try a negative value, -1 will give 123.452->120

grids = [i for i in arcpy.da.SearchCursor(fc,['SHAPE@X','SHAPE@Y','OID@'])] #List all grids with coords and objectid
grids.sort(key=lambda k: (round(k[1],decimals),round(-k[0],decimals)), reverse=True) #Sort by coords
order = [i[2] for i in grids] #Fetch objectids from sorted grids
d = {k:v for (v,k) in list(enumerate(order))} #Add counting number to each objectid as a dictionary of id:counting number


#Update field
with arcpy.da.UpdateCursor(fc,['OID@',field_to_update]) as cursor:
for row in cursor:
row[1]=d[row[0]]+1
cursor.updateRow(row)

Note the highlighted numbers. enter image description here


No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...