I have a polygon feature class with attribute fields 'name', 'rank' and 'area' in an Esri file geodatabase.
For each name there are multiple features (polygons) in the feature class. So let's say 5 polygons named 'Eva', 3 polygons named 'John' and 1 polygon named 'Ernest'. The attribute field 'area' is filled with the area and the attribute field 'rank' is still empty (int).
I want to rank the polygons by size, for every unique name. So the largest polygon for each name to be ranked 1, the second largest polygon 2, etc.
Result: there's a polygon numbered 1 for each John, Ernest and Eva; there's a polygon numbered 2 for John and Eva, there's a polygon number 3 for John and Eva, there's a polygon numbered 4 for Eva and a polygon numbered 5 for Eva. That about it.
Auto incrementing field based on groups within feature class? did the trick filling the rank field with values, but the ranking appeared to be random. Sorting on the area field did not change the situation.
With a bit of Esri help and a colleague we came up with this Python script, which I want to share with you all:
import arcpy
from itertools import count, groupby
layer = "object"
fields = ["name","area", "rank"]
sql = "ORDER BY name, area DESC"
with arcpy.da.UpdateCursor(layer,fields, sql_clause=(None,sql)) as cur:
for k,g in groupby(cur, key=lambda x: x[0]):
ctr = count(1)
for row in g:
cur.updateRow(row[:-1] + [next(ctr)])