Create sequential unique ID field based on an advanced sorting

9274
17
Jump to solution
04-30-2015 07:33 PM
AndrewNeedham
New Contributor III

Hi All

Is it possible to create sequential unique ID field based on an advanced sorting of the attributes using Python? And without installing ET GeoWizards? (ArcGIS 10.2)

This doesn't work

38517 - Create sequential numbers in a field using Python in the Field Calculator

ET GeoWizards

SOLUTION for adding new sequential ID numbers based on sorted data

Cheers

0 Kudos
17 Replies
DanPatterson_Retired
MVP Emeritus

​Me thinks he is no longer interested having found a solution on one of several sites he posted the question on... python - Creating multiple fields with ranks using arcpy - Stack Overflow   which references an Arcpy article  Ranking field values | ArcPy Café  with the cavaet that it doesn't work in these situations...

" Note: dBase (and shapefiles) does not support ORDER BY as used above by arcpy.da.UpdateCursor’s sql_clause argument. "

BlakeTerhune
MVP Regular Contributor

Looks like the solution posted there is very similar to mine. Thanks for the follow-up Dan.

0 Kudos
AndrewNeedham
New Contributor III

Hi Dan, It's been the weekend here, hence why I haven't responded. I will check the code as soon as I can. Also this is the only post on this subject I have created.  

AndrewNeedham
New Contributor III

Hi Blake,

Thanks for the code, I'll see how this works as soon as I can.

Cheers

0 Kudos
AndrewNeedham
New Contributor III

Blake, I tried the code but It didn't populate the new field.

I'll just stick to the Excel way as is will be quicker. 

0 Kudos
BlakeTerhune
MVP Regular Contributor

If you like, post the code you used and we can help you debug it.

I just tested my logic and it worked in a file geodatabase. Here is updated code that is a little more flexible.

def main():
    import arcpy
    import os

    temp_gdb = r"N:\TechTemp\BlakeT\Work\TEMP.gdb"
    fc = os.path.join(temp_gdb, "TEMP_Line")
    sortFieldName = "Note1"
    seqFieldName = "SeqID"

    # Step 1
    existingFields = [field.name for field in arcpy.ListFields(fc)]
    if seqFieldName not in existingFields:
        arcpy.AddField_management(fc, seqFieldName, "SHORT")

    # Step 2
    cursorFields = [sortFieldName, seqFieldName]
    sql_postfix = 'ORDER BY {}'.format(sortFieldName)
    with arcpy.da.UpdateCursor(fc, cursorFields, sql_clause=(None, sql_postfix)) as u_cursor:
        # Step 3
        for seqid, row in enumerate(u_cursor, start=1):
            # Step 4
            row[1] = seqid
            u_cursor.updateRow(row)


if __name__ == '__main__':
    main()
AndrewNeedham
New Contributor III

Thanks Blake,

0 Kudos
ChadFoster1
New Contributor III

Awesome, I tweaked it a bit more to allow for setup as a tool with parameters, NICE WORK!