I am trying to sort (alphabetize City) a column, and sequentially number a separate column for the purpose of labeling and creating a map key.
What is the best way to do this?
The old-school version of the update cursor will do what you want pretty easily. I'm guessing you're working in ArcGIS? If so, here's what you do. Open ArcMap, add your city layer into your mxd, and create a field for the sort order, if it doesn't already exist. (And maybe start an edit session in case something goes wrong and you want to undo it.)
You'll want to run the following code from the python window, not from the field calculator. To get to that, go to "Geoprocessing" in the menu along the top of your screen and click on "Python". An empty python window will appear. The code below is what you'll want to type. In the example below, I have a feature class named "Cities". "NAME" is the field I want to sort by, and "SortFld" is the field I want to hold my new sequential numbers, so you'll want to replace those values with the name of your feature class and the name of your fields.
counter = 1 rows = arcpy.UpdateCursor("Cities","","","NAME; SortFld", "NAME") for row in rows: row.SortFld = counter counter = counter + 1 rows.updateRow(row)
Then just hit enter. If this works for you, you can right-click on the python window and click "Save As" and save that little bit of code. Then you right-click on the window and choose "Load" to bring it back in and run it again in the future.
You can get more info on the update cursor here.
The best way depends on too many things that you have not mentioned. Is this to only be done once or every time you update the FC/table? Does the sort have to be reflected by the ObjectID or is the sort good enough if it just happens in memory and is reflected in the numbering order of separate column only?
Anyway, the Sort tool is the easiest way to create a new FC/table with the records sorted and then the ObjectID will be sequentially ordered. However, that is only a one time fix and has to be repeated if you add rows.
A Python script with a cursor can update the separate column if the records do not have to actually be stored with the ObjectIDs in order. But you have to be more specific about what you need before I will suggest any specific code.