I have an attribute
table with three fields: Id
, Name
, and Id_2
and 18,701 records. I would like to populate Id_2
with consecutive integers for each unique value in the Name
field. Prior to running the script, Id_2
is empty. Below is an example of what I would like the final attribute table to look like.
Below is the python script that I have developed. Note that I have built a dictionary using the Name
field as the keys and the Id
field as the values. I don't need to use the values, however, to accomplish this task, just the key. My code produces consecutive integers, however, the sequence doesn't reset with each unique value in the Name
field. Rather, my code populates Id_2
with consecutive integers for the entire table, through record 18,701 (Not what I want!).
# import required python libraries or modules
import arcpy
import traceback
# settings
arcpy.env.workspace = r'D:/test'
arcpy.env.overwriteOutput = True
# variables
fc = r'D:/test/colors.shp'
fields = ['Id', 'Name', 'Id_2']
for f in fields:
print f, f in [field.name for field in arcpy.ListFields(fc)]
# build dictionary
rnDict = {}
cursor = arcpy.da.SearchCursor(fc, fields)
try:
for row in cursor:
id = row[0]
rn = row[1]
rnDict.setdefault(rn, []).append(id)
print 'dictionary successfully built'
except:
print 'An error occurred - part 2'
traceback.print_exc()
del cursor
# update Id_2 field with sequential integers
startNumber = 1
cursor = arcpy.da.UpdateCursor(fc, fields) # type: object
try:
for row in cursor2:
name = row[1]
if name in rnDict:
row[2] = startNumber
startNumber = startNumber + 1
cursor2.updateRow(row)
print 'completed consecutive numbering'
except:
print 'An error occurred during calculating field'
traceback.print_exc()
del cursor
# del rnDict