Rank features by an attribute within groups of another attribute

1166
1
05-13-2021 11:53 AM
Labels (3)
LeilaJackson1
Occasional Contributor III

Using the below code in ArcGIS Pro Calculate Field, I was able to rank my data overall by score (descending - so high score gets a rank of 1) after permanently sorting my layer, but I would also like to rank scores within groups of 1 or 2 other fields for example within Watershed and within Watershed and County. Is there a way to add this to the code in Calculate Field?

Rank=getNextRank(!Score!)

Code Block

rank = 0
lastValue = None

def getNextRank(value):
global rank
global lastValue
if value == lastValue:
return rank
else:
rank+=1
lastValue = value
return rank

For example

ScoreWatershedCountyOverall RankRank_win_WatershedRank_win_WatershedCounty
30A1521
10A1732
70A2111
25B1621
40B2411
30C1531
60C2211
55C2322

 

Many thanks!

0 Kudos
1 Reply
JoshuaBixby
MVP Esteemed Contributor

It is much easier with multi-group ranking to use cursors rather than Field Calculator.  Something like this in the interactive Python window should work:

lyr = # name of layer or path to feature class or table

sql = "ORDER BY watershed, county, score desc"
flds = ["watershed", "county", "Rank_win_WatershedCounty"]
with arcpy.da.UpdateCursor(lyr, flds, sql_clause=(None,sql)) as cur:
    cnt = 1
    row = next(cur)
    cur.updateRow(row[0:2] + [cnt])
    row_prev = row
    for row in cur:
        if row[0:2]==row_prev[0:2]:
            cnt += 1
        else:
            cnt = 1
            
        cur.updateRow(row[0:2] + [cnt])
        row_prev = row