I have a dataset with ranked attributes(e.g. very low, low, moderate, high, very high). I would like to write a python code using arcpy to give a numeric values to each rank, such as 0,5,10,20,50,100. I created a new field to save these values, and I am now struggling to write a simple code that translate each rank to a numeric value. any ideas ?
Since you've already created your field to store the integer ranks you can use the Field Calculator with the following codeblock (this code assumes your string, or text, ranks are stored in the field rank and your new field for storing the integer ranks is num_rank):
For each feature in your dataset, the corresponding rank value (very low, low, moderate, high, very high) is pushed into the calc_num_rank function. In that function the text form of the rank is mapped to a numeric value; it is this numeric value that is returned as your num_rank value.
Your dataset's attributes should then look similar to this:
Note: The code inside the codeblock makes use of a dictionary to store the string and corresponding numeric rank values. You can expand/edit this dictionary to match your dataset's attributes and desired numeric rankings. If you are unfamiliar with dictionaries in python check out this page.
This is another way
rank_dictionary = {'very low':0, 'low':5, 'moderate':20,'high':50, 'very high':100}
shapefile = 'dataset'
fields = ['Rank_txt', 'Rank_num']
with arcpy.da.UpdateCursor(shapefile, fields) as Cursor:
for row in Cursor:
row[1] = rank_dictionary.get(row[0])
Cursor.updateRow(row)
This will get you started. My assumption is that RANK is your attribute string field and RANK_NUM is your rank numerical value field.
attributes = [['very low',0], ['low',5], ['moderate',20], ['high',50], ['very high',100]]
dataset_lyr = "dataset_lyr"
arcpy.MakeFeatureLayer_management("dataset.shp", dataset_lyr)
for att in attributes:
selection = '"' + "RANK = '" + att[0] + "'" +'"'
selection_type = "NEW_SELECTION"
arcpy.SelectLayerByAttribute_management (dataset_lyr, selection_type,selection)
arcpy.CalculateField_management(dataset_lyr, "RANK_NUM", att[1], "PYTHON_9.3","")