Mike
Mike

Reputation: 4405

Populate Unique ID field after Sorting, Python

I am trying to create an new unique id field in an access table. I already have one field called SITE_ID_FD, but it is historical. The format of the unique value in that field isn't what our current format is, so I am creating a new field with the new format.

Old Format = M001, M002, K003, K004, S005, M006, etc

New format = 12001, 12002, 12003, 12004, 12005, 12006, etc

I wrote the following script:

fc = r"Z:\test.gdb\testfc"

x = 12001

cursor = arcpy.UpdateCursor(fc)

for row in cursor:
    row.setValue("SITE_ID", x)
    cursor.updateRow(row)
    x+= 1

This works fine, but it populates the new id field based on the default sorting of objectID. I need to sort 2 fields first and then populate the new id field based on that sorting (I want to sort by a field called SITE and then by the old id field SITE_ID_FD)

I tried manually sorting the 2 fields in hopes that Python would honor the sort, but it doesn't. I'm not sure how to do this in Python. Can anyone suggest a method?

Upvotes: 0

Views: 1347

Answers (2)

Eytan
Eytan

Reputation: 798

A possible solution is when you are creating your update cursor. you can specify to the cursor the fields by which you wish it to be sorted (sorry for my english..), they explain this in the documentation: http://help.arcgis.com/en/arcgisdesktop/10.0/help/index.html#//000v0000003m000000

so it goes like this: UpdateCursor(dataset, {where_clause}, {spatial_reference}, {fields}, {sort_fields}) and you are intrested only in the sort_fields so assuming that your code will work well on a sorted table and that you want the table ordered asscending the second part of your code should look like this:

fc = r"Z:\test.gdb\testfc"

x = 12001

cursor = arcpy.UpdateCursor(fc,"","","","SITE A, SITE_ID_FD A") 
#if you want to sort it descending you need to write it with a D 
#>>  cursor = arcpy.UpdateCursor(fc,"","","","SITE D, SITE_ID_FD D")

for row in cursor:
    row.setValue("SITE_ID", x)
    cursor.updateRow(row)
    x+= 1

i hope this helps

Upvotes: 2

selllikesybok
selllikesybok

Reputation: 1225

Added a link to the arcpy docs in a comment, but from what I can tell, this will create a new, sorted dataset--

import arcpy
from arcpy import env

env.workspace = r"z:\test.gdb"

arcpy.Sort_management("testfc", "testfc_sort", [["SITE", "ASCENDING"],
                                                ["SITE_IF_FD", "ASCENDING]])

And this will, on the sorted dataset, do what you want:

fc = r"Z:\test.gdb\testfc_sort"
x = 12001
cursor = arcpy.UpdateCursor(fc)

for row in cursor:
    row.setValue("SITE_ID", x)
    cursor.updateRow(row)
    x+= 1

I'm assuming there's some way to just copy the sorted/modified dataset back over the original, so it's all good?

I'll admit, I don't use arcpy, and the docs could be a lot more explicit.

Upvotes: 0

Related Questions