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
Score | Watershed | County | Overall Rank | Rank_win_Watershed | Rank_win_WatershedCounty |
30 | A | 1 | 5 | 2 | 1 |
10 | A | 1 | 7 | 3 | 2 |
70 | A | 2 | 1 | 1 | 1 |
25 | B | 1 | 6 | 2 | 1 |
40 | B | 2 | 4 | 1 | 1 |
30 | C | 1 | 5 | 3 | 1 |
60 | C | 2 | 2 | 1 | 1 |
55 | C | 2 | 3 | 2 | 2 |
Many thanks!
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