Rank values in a field using python

3409
1
04-15-2011 07:34 AM
ErikMartin
Occasional Contributor
Greetings,

I am trying to take values in one field and write the ranks for those values to a new field.  For example:

3 -> 2
2 -> 1
5 -> 3
6 -> 4
9 -> 6
7 -> 5

In an ideal world, I'd like to deal with ties in a particular way (as follows), but one step at a time...

3 -> 2
2 -> 1
2 -> 1
2 -> 1
5 -> 3
9 -> 5
7 -> 4

Using numpy and scipy, I have gotten this to work using just Python (PythonWin), outside of ArcMap.  The following averages the ranks of ties, which is good enough for now:

import numpy
import scipy
from scipy import stats

x=numpy.ma.array([0,1,1,1,2,2,4,4,5,6])
rank = stats.mstats.rankdata()
print rank


Results in:
[[  1    3    3    3    5.5   5.5   7.5   7.5   9   10 ]]

At this point, i am trying to figure out how to pass values from a field into the input array and then write the results back to the other field.  I'm not sure if a cursor is the best way to do this, or if all the values in a field can be passed into an array.  Again, I'm a python newbie, so any ideas or suggestions are welcome.
Thanks,
-Erik
0 Kudos
1 Reply
DarrenWiens2
MVP Honored Contributor
I believe you need to use a cursor to pass the values one at a time. To read fields values, use SearchCursor. To write values, use UpdateCursor or InsertCursor. Make sure you take advantage of the sorting capabilities, especially for your ranking question.

PS - there's a forum specifically for Python, where you'll probably get your questions answered faster.
0 Kudos