Calculate a unique value for each record

In this example, a unique value is calculated for each record starting with 1. The result is 1, 2, 3 … to the number of records. This is often necessary when you have to do some spatial operation and perform a join or relate using that field. It can also be useful when your table doesn’t have an OBJECTID field.

This code uses the data access module available with ArcGIS 10.1.

import arcpy
with arcpy.da.UpdateCursor(r"C:\Data\city.gdb\crime", "UID") as rows:
    for i, row in enumerate(rows, 1):
        row[0] = i
        rows.updateRow(row)

2 thoughts on “Calculate a unique value for each record

  1. Good post and nice use of the with statement with the DA cursors. Using the start option of enumerate saves the overhead of addition within the loop

    import arcpy
    with arcpy.da.UpdateCursor(r”C:\Data\city.gdb\crime”, “UID”) as rows:
    for i, row in enumerate(rows, 1):
    row[0] = i
    rows.updateRow(row)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s