[GIS] How to assign a unique ID to groups of items in the attribute table in ArcMap

field-calculatorlooppython

Using arcmap's field calculator I need to programatically loop through all of the entries in the field and for each name it gets its own unique id. So names that are the same would get the same number. This is done through model builder.

def NameReclass(name):
foreach name in species …. etc.

I'm just really confused how to do this without if/elif statements and specifying the string name == 1, etc. because it needs to be an id for each name shown.

Best Answer

You can use the Python setdefault() method and an UpdateCursor to do this.

import arcpy

fc = r'C:\temp\your_shapefile.shp'

# create an empty dictionary
convert = {}

# Start an update cursor and add unique ID based on unique string value
with arcpy.da.UpdateCursor(fc, ["species", "code"]) as cursor:
    for row in cursor:
        row[1] = convert.setdefault(row[0], len(convert))
        cursor.updateRow(row)

To illustrate what is going on behind the scenes, setdefault() adds a new key and unique value for every new species it encounters:

>>> str2id
{u'A': 0, u'B': 1, u'C': 2}
>>>

enter image description here

Related Question