Add value in attribute field using arcpy

I've not used Arc 10.1 cursors, but it's apparently even easier there.

In 10.0, there are a few ways to go about it, but here's a basic, beginner's approach:

# Create a cursor on a feature class
cur = arcpy.UpdateCursor(myFeatureClass)

# Loop through the rows in the attribute table
for row in cur:
    # The variable sqMiles will get the value from the column
    # named 'Area_Miles'
    sqMiles = row.getValue('Area_Miles')
    # Calculate how many acres
    acres = (sqMiles * 640)
    # Assign the acres to a column named 'Area_Acres'
    row.setValue('Area_Acres', acres)
    # Apply the change
    cur.updateRow(row)

    # The loop will then move on to the next row/feature

A simpler, condensed version:

cur = arcpy.UpdateCursor(myFeatureClass)

for row in cur:
    row.setValue('Area_Acres', row.getValue('Area_Miles') * 640)
    cur.updateRow(row)

See: http://help.arcgis.com/en/arcgisdesktop/10.0/help/index.html#//000v0000003m000000


Well, there are a few ways you can do this.

  1. If the calculation is fairly simple, I would use the Calculate Field tool. If you need to use the code_block parameter, I'd go with option #2 as it's not always easy getting the syntax correct in a script (or in the tool itself for that matter).

  2. If you are interested in scripting more in the future, I'd strongly recommend using cursors. You can write the values from one field into a Python list and perform your calculations on each item in the list with a for loop and then write the list back to your new field.

I rarely use Calculate Field anymore as it's easier to script cursors for all but the simplest formulas.

Tags:

Arcpy