Calculating (with Python) a 2nd field based on a 1st field in 10.2

2128
5
01-08-2014 09:46 AM
JoelGuerra
New Contributor
I am attempting to write a script that takes one field and sorts it from largest to smallest. I then want to add another field next to the sorted field in order to indicate a sequential order of the first field (ranging from 1 to what ever is the last occurence is). In other words, calculate a numeric sequential order of a field and populate that field with numbers based and in conjunction with another field. Is it possible? Any tips ?
Tags (2)
0 Kudos
5 Replies
JasonScheirer
Occasional Contributor III
This doesn't account for multiples of the same value, but it'd work:

table = "my_table"
field_to_sort = "a"
field_to_rank = "b"

# Make a sorted set of values in table
with arcpy.da.cursor(table, field_to_sort) as cursor:
    sorted_items = sorted( { row[0] for row in cursor } )

# Rank based on order
sorted_ranking = { item: index + 1 for index, item in enumerate(sorted_items) }

with arcpy.da.UpdateCursor(table, [field_to_sort, field_to_rank]) as cursor:
    for value, rank_value in cursor:
        new_rank_value = sorted_ranking[value]
        cursor.updateRow([value, new_rank_value])
0 Kudos
JoelGuerra
New Contributor
I'll certainly give this a try. Thank you!
0 Kudos
JoelGuerra
New Contributor
Looking it over I noticed the work space was not set. I'm assuming the code here comes after the workspace is set right? Sorry, I'm a newbie to Python. 🙂
0 Kudos
JoelGuerra
New Contributor
When running the script, it seems to have a problem with one of the lines. This is the error that is coming up;

with arcpy.da.cursor(table, field_to_sort) as cursor:
Attribute Error: 'module' object has no attribute 'cursor'




Just a reminder also, the "field_to_rank" variable is one that needs to be created in the table.
0 Kudos
JoelGuerra
New Contributor
Also when entering the table in question (the table that is supposed to have its fields sorted), can I just put in/reference the shape file itself, or does it needs to be an actual excel or dbf table?
0 Kudos