Select to view content in your preferred language

Sort Field and then Calculate Sequential Values

6989
15
06-22-2018 10:40 AM
deleted-user-jxpbpbjlZInj
Deactivated User

I have ZERO experience with ArcPy, Arcade expressions... yadda yadda. I basically limp along until something magically works and I'm a huge fan of Copy/Paste. THAT SAID, I'm dipping my toe into something that I thought would be easy...

I have a bunch of campgrounds, and these are in some parks. I want to give them sequential values based on sorting the PARK_NAME field alphabetically. Using Python 3 in Field Calculator, "Sequential Number" will only assign sequential values based on the Object ID field - it doesn't care how I've sorted it.

How do I tell it to use my sorted field instead of the Object ID? Help! 

15 Replies
deleted-user-jxpbpbjlZInj
Deactivated User

Lulz. Not an option! I have a bunch of feature layers to iterate through and give unique IDs to. With the Enterprise geodatabase, this happens OFTEN with scripts - my coworker suspects that it's failing because it's wanting to know WHICH version to edit. Built in tools never seem to have this issue.

0 Kudos
DanPatterson_Retired
MVP Emeritus

probably the case, I don't work in or on the Enterprise, so there is only 1 version (except for backups) and 1 editor.  That is what the expensive software is expected to handle.  I couldn't even test in all environments and configurations... so whatever gets written in one night goes out the door

deleted-user-jxpbpbjlZInj
Deactivated User

Understand! Bummertown. Thank you for sticking it out and helping, though.

0 Kudos
JoshuaBixby
MVP Esteemed Contributor

Does the following work for you when the table is in your EGDB?

from itertools import count, groupby
from operator import itemgetter

tbl = # path to table
case_fields = ["PARK_NAME", "OJBECTID"]
increment_field = ["CampgroundID"]
sql_orderby = "ORDER BY {}".format(", ".join(case_fields))

with arcpy.da.UpdateCursor(
   tbl,
   case_fields + increment_field,
   sql_clause=(None, sql_orderby)
) as cursor:
    counter = count()
    case_func = itemgetter(*(cursor.fields.index(fld) for fld in case_fields))
    for key, group in groupby(cursor, case_func):
          for row in group:
              cursor.updateRow(list(key) + ["{:0>3}".format(next(counter))])
ZulfadliSalleh
New Contributor

Thank you, the tool has solved the issue of the task I'm working on.

0 Kudos
DenizTuran
Emerging Contributor

I had the same issue and finally found the script to create sequential values NOT based on ObjectID but related to any other defined column here: https://mediaspace.esri.com/media/t/1_1fkt56w1

 

0 Kudos