Calculate Field (Data Management)

Summary

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

Usage

    Caution:

    This tool modifies the input data. See Tools that modify or update the input data for more information and strategies to avoid undesired data changes.

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

    To learn more about Arcade expressions, see ArcGIS Arcade in the Developer help.

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

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

  • This tool's Arcade expressions use the Field Calculation Arcade profile. An Arcade profile is a context in which an Arcade expression is evaluated and understood. When an Arcade expression is evaluated, the return value is cast to the field type of the output value.

  • 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. To preserve the original values, make a copy of the input table as a backup, or use the Enable Undo option in the Geoprocessing pane.

  • 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).

  • Note:

    To transfer temporal values between field types (Date, Date Only, Time Only, Timestamp Offset, and Text), use the Convert Temporal Field tool instead.

  • 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, provide the numeric value in the Expression parameter with no quotation marks around the value.

  • Legacy:

    arcgis.rand() is no longer supported as of ArcGIS Pro 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. Provide 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.

  • To calculate geometry information in Python, use Geometry object properties. For example, use an expression of !shape.pointCount! to calculate the number of vertices in a feature.

    Note:

    The Calculate Geometry Attributes tool supports similar calculations.

    To calculate area and length in Python, use the getArea and getLength methods with a method and unit type.

    • To calculate the geodesic area of polygons in square kilometers, use the following expression:
      !shape.getArea('GEODESIC', 'SQUAREKILOMETERS')!
    • To calculate the planar length of polylines (or polygons) in yards, use the following expression:
      !shape.getLength('PLANAR', 'YARDS')

    See the ArcPy Polygon and Polyline objects for more information.

    Learn more about geoprocessing tools and linear and areal units

  • 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 file is written using UTF-16-LE encoding. A file with any other encoding will not load into the code block.

  • When working with joined data, you can only update fields from the origin table. You cannot update fields from the joined table. To perform a calculation on the joined table, perform the calculation directly on that table.

  • Python expressions that attempt to concatenate string fields that include a null or divide by zero value will return 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.
    • Undoing geoprocessing operations is not supported.

    See your database vendor documentation for SQL expression help.

  • The Expression parameter on the tool dialog box has an Insert Values drop-down list where you can add field values from the selected field in the Fields list or domain values from the selected field's domain. Use the domain values to ensure that only valid values for the field domain are inserted into the field.

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.

If the input is a feature service, the default expression type is SQL. For any other type of input, the default expression type is Python.

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

To learn more about Arcade expressions, see ArcGIS Arcade in the Developer help.

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.

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

  • PythonThe Python expression type will be used.
  • ArcadeThe Arcade expression type will be used.
  • SQLThe SQL expression type will be used.
  • VBScriptThe VBScript expression type will be used.
String
Code Block
(Optional)

A block of code that will be used for complex Python or VBScript 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 field will have a length of 512, unless the input is a shapefile or dBASE file, in which case the length will be 254. To adjust the length, use the Alter Field tool.

  • 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.
  • Big integer (64-bit integer)The field type will be big integer. Big integer fields support whole numbers between -(253) and 253.
  • 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.
  • TextThe field type will be text. Text fields support a string of characters.
  • DateThe field type will be date. Date fields support date and time values.
  • Date (high precision)The field type will be high precision date. High precision date fields support date and time values with millisecond time.
  • Date onlyThe field type will be date only. Date only fields support date values with no time values.
  • Time onlyThe field type will be time only. Time only fields support time values with no date values.
  • Timestamp offsetThe field type will be timestamp offset. Timestamp offset fields support a date, time, and offset from a UTC value.
  • 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.
  • GUID (globally unique identifier)The field type will be GUID. GUID fields store registry-style strings consisting of 36 characters enclosed in curly brackets.
  • Raster The 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.
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.
  • ARCADEThe Arcade expression type will be used.
  • SQLThe SQL expression type will be used.
  • VBThe VBScript expression type will be used.

If the input is a feature service, the default expression type is SQL. For any other type of input, the default expression type is PYTHON3.

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

To learn more about Arcade expressions, see ArcGIS Arcade in the Developer help.

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.

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

String
code_block
(Optional)

A block of code that will be used for complex Python or VBScript 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 field will have a length of 512, unless the input is a shapefile or dBASE file, in which case the length will be 254. To adjust the length, use the Alter Field tool.

  • 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.
  • BIGINTEGERThe field type will be big integer. Big integer fields support whole numbers between -(253) and 253.
  • 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.
  • TEXTThe field type will be text. Text fields support a string of characters.
  • DATEThe field type will be date. Date fields support date and time values.
  • DATEHIGHPRECISIONThe field type will be high precision date. High precision date fields support date and time values with millisecond time.
  • DATEONLYThe field type will be date only. Date only fields support date values with no time values.
  • TIMEONLYThe field type will be time only. Time only fields support time values with no date values.
  • TIMESTAMPOFFSETThe field type will be timestamp offset. Timestamp offset fields support a date, time, and offset from a UTC value.
  • 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.
  • GUIDThe field type will be GUID. GUID fields store registry-style strings consisting of 36 characters enclosed in curly brackets.
  • RASTER The 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.
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.

Licensing information

  • Basic: Yes
  • Standard: Yes
  • Advanced: Yes

Related topics