Calculate Field (Data Management)

Summary

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

Usage

  • To learn more about Python expressions, see Calculate Field Python examples.

    To learn more about Arcade expressions, see the ArcGIS Arcade guide.

    To learn more about SQL expressions, see Calculate field values.

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

  • The calculation can only be applied to one field per operation. To apply multiple calculations, use the Calculate Fields tool.

  • Existing field values will be overwritten. Make a copy of the input table if you want to preserve the original values.

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

    For Arcade calculations, field names must be prefixed with $feature. (for example, $feature.fieldname).

  • To calculate strings to text or character fields, on the dialog box, the string must use double quotation marks (for example, "string"), or in scripting, the string using double quotation marks must also be enclosed in single quotation marks (for example, '"string"').

  • To calculate a field to be a numeric value, enter the numeric value in the Expression parameter with no quotation marks around the value.

  • Legacy:

    arcgis.rand() is no longer supported as of AllSource 2.0. Comparable functions using Python's random module should be used instead. To use the random module successfully, add it as an import in the Code Block parameter.

  • You can create complex expressions using the Code Block parameter. Enter the code block either directly on the dialog box or as a string in scripting. The expression and code block are connected. The code block must relate back to the expression; the result of the code block must be passed to the expression.

    The Code Block parameter is only supported for Python expressions.

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

  • Python expressions can be created using properties from the Geometry object, including type, extent, centroid, firstPoint, lastPoint, area, length, isMultipart, and partCount (for example, !shape.area!).

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

    Learn more about geoprocessing tools and linear and areal units

  • Python expressions can be used to calculate the geodesic area or length of a feature using the geodesicArea or geodesicLength properties combined with areal or linear units of measure (for example, !shape.geodesicArea@hectares! or !shape.geodesicLength@miles!).

  • ArcGIS applications use UTF-16-LE encoding to read and write .cal files. Other applications (for example, Notepad) can be used to create or modify .cal files as long as the output is written using UTF-16-LE encoding. Using any other encoding will result in a file that will not load into the code block.

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

  • Python expressions that attempt to concatenate string fields that include a null or divide by zero value will return a null for that field value.

  • SQL expressions support faster calculations for feature services and enterprise geodatabases. Instead of performing calculations one feature or row at a time, a single request is sent to the server or database, resulting in faster calculations.

    Only feature services and enterprise geodatabases support SQL expressions. For other formats, use Python or Arcade expressions.

    Using the SQL option for the Expression Type parameter has the following limitations:

    • The option is only supported for Db2, Oracle, PostgreSQL, SAP HANA, and SQL Server enterprise geodatabases.
    • Calculating field values on joined tables is not supported.
    • Versioned and archived enterprise geodatabase data is not supported.
    • The ability to undo geoprocessing operations is not supported.

    See your database vendor documentation for SQL expression help.

Parameters

LabelExplanationData Type
Input Table

The table containing the field that will be updated with the new calculation.

Mosaic Layer; Raster Layer; Table View
Field Name (Existing or New)

The field that will be updated with the new calculation.

If a field with the specified name does not exist in the input table, it will be added.

Field
Expression

The simple calculation expression used to create a value that will populate the selected rows.

SQL Expression
Expression Type
(Optional)

Specifies the type of expression that will be used.

To learn more about Python expressions, see Calculate Field Python examples.

To learn more about Arcade expressions, see the ArcGIS Arcade guide.

To learn more about SQL expressions, see Calculate field values.

SQL expressions support faster calculations for feature services and enterprise geodatabases. Instead of performing calculations one feature or row at a time, a single request is sent to the server or database, resulting in significantly faster calculations.

Only feature services and enterprise geodatabases support SQL expressions. For other formats, use Python or Arcade expressions.

  • Python 3The Python expression type will be used. This is the default.
  • ArcadeThe Arcade expression type will be used.
  • SQLThe SQL expression type will be used.
String
Code Block
(Optional)

A block of code that will be entered for complex expressions.

String
Field Type
(Optional)

Specifies the field type of the new field. This parameter is only used when the field name does not exist in the input table.

If the field is of type text, the new field will have a length of 512. For shapefiles and dBASE files, the field will have a length of 254. The length of the new field can be adjusted using the Alter Field tool.

  • TextThe field type will be text. Text fields support a string of characters.
  • Float (32-bit floating point)The field type will be float. Float fields support fractional numbers between -3.4E38 and 1.2E38.
  • Double (64-bit floating point)The field type will be double. Double fields support fractional numbers between -2.2E308 and 1.8E308.
  • Short (16-bit integer)The field type will be short. Short fields support whole numbers between -32,768 and 32,767.
  • Long (32-bit integer)The field type will be long. Long fields support whole numbers between -2,147,483,648 and 2,147,483,647.
  • DateThe field type will be date. Date fields support date and time values.
  • Blob (binary data)The field type will be BLOB. BLOB fields support data stored as a long sequence of binary numbers. You need a custom loader or viewer or a third-party application to load items into a BLOB field or view the contents of a BLOB field.
  • Raster imageryThe field type will be raster. Raster fields can store raster data in or alongside the geodatabase. All ArcGIS software-supported raster dataset formats can be stored, but it is recommended that only small images be used.
  • GUID (globally unique identifier)The field type will be GUID. GUID fields store registry-style strings consisting of 36 characters enclosed in curly brackets.
String
Enforce Domains
(Optional)

Specifies whether field domain rules will be enforced.

  • Checked—Field domain rules will be enforced. If a field cannot be updated, the field value will remain unchanged, and the tool messages will include a warning message.
  • Unchecked—Field domain rules will not be enforced. This is the default
Boolean

Derived Output

LabelExplanationData Type
Updated Input Table

The updated table.

Table View; Raster Layer; Mosaic Layer

arcpy.management.CalculateField(in_table, field, expression, {expression_type}, {code_block}, {field_type}, {enforce_domains})
NameExplanationData Type
in_table

The table containing the field that will be updated with the new calculation.

Mosaic Layer; Raster Layer; Table View
field

The field that will be updated with the new calculation.

If a field with the specified name does not exist in the input table, it will be added.

Field
expression

The simple calculation expression used to create a value that will populate the selected rows.

SQL Expression
expression_type
(Optional)

Specifies the type of expression that will be used.

  • PYTHON3The Python expression type will be used. This is the default.
  • ARCADEThe Arcade expression type will be used.
  • SQLThe SQL expression type will be used.

To learn more about Python expressions, see Calculate Field Python examples.

To learn more about Arcade expressions, see the ArcGIS Arcade guide.

To learn more about SQL expressions, see Calculate field values.

SQL expressions support faster calculations for feature services and enterprise geodatabases. Instead of performing calculations one feature or row at a time, a single request is sent to the server or database, resulting in significantly faster calculations.

Only feature services and enterprise geodatabases support SQL expressions. For other formats, use Python or Arcade expressions.

String
code_block
(Optional)

A block of code that will be entered for complex expressions.

String
field_type
(Optional)

Specifies the field type of the new field. This parameter is only used when the field name does not exist in the input table.

If the field is of type text, the new field will have a length of 512. For shapefiles and dBASE files, the field will have a length of 254. The length of the new field can be adjusted using the Alter Field tool.

  • TEXTThe field type will be text. Text fields support a string of characters.
  • FLOATThe field type will be float. Float fields support fractional numbers between -3.4E38 and 1.2E38.
  • DOUBLEThe field type will be double. Double fields support fractional numbers between -2.2E308 and 1.8E308.
  • SHORTThe field type will be short. Short fields support whole numbers between -32,768 and 32,767.
  • LONGThe field type will be long. Long fields support whole numbers between -2,147,483,648 and 2,147,483,647.
  • DATEThe field type will be date. Date fields support date and time values.
  • BLOBThe field type will be BLOB. BLOB fields support data stored as a long sequence of binary numbers. You need a custom loader or viewer or a third-party application to load items into a BLOB field or view the contents of a BLOB field.
  • RASTERThe field type will be raster. Raster fields can store raster data in or alongside the geodatabase. All ArcGIS software-supported raster dataset formats can be stored, but it is recommended that only small images be used.
  • GUIDThe field type will be GUID. GUID fields store registry-style strings consisting of 36 characters enclosed in curly brackets.
String
enforce_domains
(Optional)

Specifies whether field domain rules will be enforced.

  • ENFORCE_DOMAINSField domain rules will be enforced.
  • NO_ENFORCE_DOMAINSField domain rules will not be enforced. This is the default.
Boolean

Derived Output

NameExplanationData Type
out_table

The updated table.

Table View; Raster Layer; Mosaic Layer

Code sample

CalculateField example 1 (Python window)

The following Python window script demonstrates how to use the CalculateField function in immediate mode.

import arcpy
arcpy.env.workspace = "C:/data"
arcpy.management.AddField("vegtable.dbf", "VEG_TYP2", "TEXT", "", "", "20")
arcpy.management.CalculateField("vegtable.dbf", "VEG_TYP2", 
                                '!VEG_TYPE!.split(" ")[-1]', "PYTHON3")
CalculateField example 2 (stand-alone script)

Use the CalculateField function to assign centroid values to new fields.

# Name: CalculateField_centroids.py

# Import system modules
import arcpy

# Set environment settings
arcpy.env.workspace = "C:/data/airport.gdb"
 
# Set local variables
inFeatures = "parcels"
fieldName1 = "xCentroid"
fieldName2 = "yCentroid"
fieldPrecision = 18
fieldScale = 11
 
# Add fields
arcpy.management.AddField(inFeatures, fieldName1, "DOUBLE", 
                          fieldPrecision, fieldScale)
arcpy.management.AddField(inFeatures, fieldName2, "DOUBLE", 
                          fieldPrecision, fieldScale)
 
# Calculate centroid
arcpy.management.CalculateField(inFeatures, fieldName1, 
                                "!SHAPE.CENTROID.X!",
                                "PYTHON3")
arcpy.management.CalculateField(inFeatures, fieldName2, 
                                "!SHAPE.CENTROID.Y!",
                                "PYTHON3")
CalculateField example 3 (stand-alone script)

Use the CalculateField function with a code block to calculate values based on ranges.

# Name: CalculateField_ranges.py

# Import system modules
import arcpy
 
# Set environment settings
arcpy.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"""
 
# Run AddField
arcpy.management.AddField(inTable, fieldName, "SHORT")
 
# Run CalculateField 
arcpy.management.CalculateField(inTable, fieldName, expression, "PYTHON3", 
                                codeblock)
CalculateField example 4 (stand-alone script)

Use the CalculateField function to assign random values to a new field.

# Name: CalculateField_Random.py

# Import system modules
import arcpy
import random
 
# Set environment settings
arcpy.env.workspace = "C:/data/airport.gdb"
  
# Set local variables
inFeatures = "parcels"
fieldName = "RndValue"
expression = "random.randint(0, 10)"
code_block = "import random"
 
# Run AddField
arcpy.management.AddField(inFeatures, fieldName, "LONG")
 
# Run CalculateField 
arcpy.management.CalculateField(inFeatures, fieldName, expression, "PYTHON3", 
                                code_block)
CalculateField example 5 (Python window)

The following Python window script demonstrates how to use the CalculateField function with ARCADE in immediate mode.

import arcpy
arcpy.env.workspace = "C:/data/fgdb.gdb"
arcpy.management.CalculateField("data", "new_value", "$feature.value1 + $feature.value2", "ARCADE")
CalculateField example 6 (Python window)

The following Python window script demonstrates how to use the CalculateField function with SQL in immediate mode.

import arcpy
feature_service = "<a feature service url>"
arcpy.management.CalculateField("data", "NEW_VALUE", "SAMPLE * (BASELINE - 40)", "SQL")

Environments

Special cases

Transfer Field Domain Descriptions

When this environment is turned on, any fields that have an associated domain will use the domain description instead of the field's value. Values from fields that do not have a domain will be unaffected.