Knowledge Base - Technical Articles


Technical Article   HowTo:  Use Python UpdateCursor method to calculate values in a table based on another field

Article ID: 35223
Software:  ArcGIS - ArcEditor 9.2, 9.3, 9.3.1 ArcGIS - ArcInfo 9.2, 9.3, 9.3.1 ArcGIS - ArcView 9.2, 9.3, 9.3.1
Platforms:  Windows XP, 2003Server, Vista

Summary

Instructions provided describe how to use the Python UpdateCursor method to calculate values in a table based on another field.

Sometimes it is desirable to set attributes in a field to certain values based on the value of another field. In this case the UpdateCursor with conditional statements can be used to correctly set those values.

Procedure

Pseudo Code:

1. Create a geoprocessor object.
2. Input the feature class to be updated.
3. Create the UpdateCursor object.
4. Iterate through the rows in the table and update the values based on the conditional statements.

# Import the standard modules and create the geoprocessor...

import arcgisscripting, os, string, sys, time
gp = arcgisscripting.create()

# Set the overwrite to true...
gp.overwriteoutput = 1

# The file to be updated...
fc = r"C:\Temp\testdata.shp"

# Create the UpdateCursor Object
cur = gp.updatecursor(fc)
row = cur.next()

while row:
# Get the value of the field the calculation will be based on...
field1 = str(row.getvalue("FIELD1"))
# Conditional Statements
# if the field1 = value1, set field2 to equal NewVal1, etc...
if field1 == "Value1":
row.FIELD2 = "NewVal1"
cur.updaterow(row)
row = cur.next()
elif field1 == "Value2":
row.FIELD2 = "NewVal2"
cur.updaterow(row)
row = cur.next()
else:
row.FIELD2 = "NewVal3"
cur.updaterow(row)
row = cur.next()

del cur, row, gp





    Related Information


    Created: 7/15/2008
    Last Modified: 5/3/2011

    If you would like to post a comment, please login