1

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.

4
  • 2
    Please include an example containing original and desired output.
    – Aaron
    Apr 16, 2015 at 19:48
  • Out of curiosity, why is using elif off the table?
    – juturna
    Apr 16, 2015 at 19:57
  • 1
    Several softwares have field calculators, so it might be helpful to specify which one. Is there one entry/word per field, or multiple (ie bird vs bird, rodent)? I believe you'll be wanting to look at either a dictionary or a CASE statement. How many possible words/numbers are there?
    – Chris W
    Apr 16, 2015 at 20:04
  • Use 2 lists, one with possible names, second with matching numbers
    – FelixIP
    Apr 16, 2015 at 20:12

2 Answers 2

3

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

1
  • cool, I didn't know about setDefault(). that looks pretty useful.
    – mr.adam
    Apr 17, 2015 at 16:07
1

This works:

caseList = [ ]

def returnCase(inValue):
   global caseList

   if not inValue in caseList:
      caseList.append(inValue)

   return caseList.index(inValue)

http://www.maprantala.com/category/esri/arcmap-esri/field-calculator/

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.