Using the Calculate Field tool

The Calculate Field tool is located in the Data Management toolbox in the Fields toolset. This is the same tool that is called when you click the Field Calculator command from the field shortcut menu of an attribute table. When performing field calculations, it is important to know what type of data you are using and in what context it is going to be used in the future. The syntax that must be used in a calculation expression differs depending on the data source and scripting language.

The following includes a number of important tips and best practices for using the Calculate Field tool.

Tips and best practices for using the Calculate Field tool

Calculates the values of a field for a feature class, feature layer, or raster catalog.

Expressions can be created using VBScript or a standard Python format. The formatting style of the string used for the expression should be appropriate for the environment (type).

Python expressions can be created using properties from the geometry object (type, extent, centroid, firstPoint, lastPoint, area, length, isMultipart, and partCount).

Python expressions can use the geometry area and length properties with an areal or linear unit to convert the value to a different unit of measure (e.g. !shape.length@kilometers!). If the data is stored in a geographic coordinate system and a linear unit (for example, miles) is supplied, the length will be calculated using a geodesic algorithm. Using areal units on geographic data will yield questionable results as decimal degrees are not consistent across the globe.

!shape.area@acres!

When used with a selected set of features, such as those created from a query in Make Feature Layer or Select Layer by Attribute, this tool will only update the selected records.

The calculation can only be applied to one field per operation.

Fields are always enclosed in brackets [ ] for VBScript.

For Python calculations, field names must be enclosed in exclamation points (!fieldname!).

To calculate strings to text or character fields, in the dialog box the string must be double-quoted ("string"), or in scripting, the double-quoted string must also be encapsulated in single quotes ('"string"').

This tool can also be used to update character items. Expressions using a character string should be wrapped, using single quotes—for example, [CHARITEM] = 'NEW STRING'. However, if the character string has embedded single quotes, wrap the string using double quotes—for example, [CHARITEM] = "TYPE'A'".

To calculate a field to be a numeric value, enter the numeric value in the Expression parameter; no quotes around the value are required.

The arcgis.rand() function is supported by the Calculate Field tool, and the expression type must be Python. The arcgis.rand() function was created for ArcGIS tools and should not be confused with the Python Rand() function.

The expression and code block are connected. The code block must relate back to the expression; the result of the code block should be passed into the expression.

The Python math module and formatting are available for use in the Code Block parameter. You can import additional modules. The math module provides number-theoretic and representation functions, power and logarithmic functions, trigonometric functions, angular conversion functions, hyberbolic functions, and mathematical constants. To learn more about the math module, see Python's help.

Saved VB .cal files from previous versions of ArcGIS may work or require minimal modifications. If you have VBA code from past releases that use ArcObjects, you will need to modify your calculations to work in 10.0.

When calculating joined data, you cannot calculate the joined columns directly. However, you can directly calculate the columns of the origin table. To calculate the joined data, you must first add the joined tables or layers to ArcMap. You can then perform calculations on this data separately. These changes will be reflected in the joined columns.

The expression type must be Python when running Calculate Field with ArcGIS Engine or ArcGIS Server. Only use Python as the expression type whenever the tool is included in a model that will be published to ArcGIS Server.

Code block examples using the Calculate Field tool

CalculateField example: Calculate centroids

Use CalculateField to assign centroid values to new fields.

# Name: CalculateField_Centroids.py
# Description: Use CalculateField to assign centroid values to new fields

 
# Import system modules
import arcpy
from arcpy import env

try: 
    # Set environment settings
    env.workspace = "C:/data/airport.gdb"
 
    # Set local variables
    inFeatures = "parcels"
    fieldName1 = "xCentroid"
    fieldName2 = "yCentroid"
    fieldPrecision = 18
    fieldScale = 11
    # Expressions are calculated using the Shape Field's geometry property
    expression1 = "float(!SHAPE.CENTROID!.split()[0])"
    expression2 = "float(!SHAPE.CENTROID!.split()[1])"
 
    # Execute AddField
    arcpy.AddField_management(inFeatures, fieldName1, "DOUBLE", 
                              fieldPrecision, fieldScale)
    arcpy.AddField_management(inFeatures, fieldName2, "DOUBLE", 
                              fieldPrecision, fieldScale)
 
    # Execute CalculateField 
    arcpy.CalculateField_management(inFeatures, fieldName1, expression1,
                                    "PYTHON")
    arcpy.CalculateField_management(inFeatures, fieldName2, expression2,
                                    "PYTHON")
except Exception, e:
    # If an error occurred, print line number and error message
    import traceback, sys
    tb = sys.exc_info()[2]
    print "Line %i" % tb.tb_lineno
    print e.message

CalculateField example: Calculate ranges

Use CalculateField with a codeblock to calculate values based on ranges.

# Name: CalculateField_Ranges.py
# Description: Use CalculateField with a codeblock to calculate values
#  based on ranges

 
# Import system modules
import arcpy
from arcpy import env
 
# Set environment settings
env.workspace = "C:/data/airport.gdb"
 
# Set local variables
inTable = "parcels"
fieldName = "areaclass"
expression = "getClass(float(!SHAPE.area!))"
codeblock = """def getClass(area):
    if area <= 1000:
        return 1
    if area > 1000 and area <= 10000:
        return 2
    else:
        return 3"""
 
# Execute AddField
arcpy.AddField_management(inTable, fieldName, "SHORT")
 
# Execute CalculateField 
arcpy.CalculateField_management(inTable, fieldName, expression, "PYTHON", 
                                codeblock)

CalculateField example: Calculate random values

Use CalculateField to assign random values to a new field.

# Name: CalculateField_Random.py
# Description: Use CalculateField to assign random values to a new field
 
  
# Import system modules
import arcpy
from arcpy import env
 
# Set environment settings
env.workspace = "C:/data/airport.gdb"
  
# Set local variables
inFeatures = "parcels"
fieldName = "RndValue"
expression = "arcgis.rand('Integer 0 10')"
 
# Execute AddField
arcpy.AddField_management(inFeatures, fieldName, "LONG")
 
# Execute CalculateField 
arcpy.CalculateField_management(inFeatures, fieldName, expression, "PYTHON")

Related Topics


9/17/2012