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 in 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 ("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 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.

  • The Code Block parameter allows you to create complex expressions. You can enter the code block directly on the dialog box or as a continuous 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 geometry area and length 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 yield questionable results, as decimal degrees are not consistent across the globe.

    • The following are areal units of measure keywords:
      • ACRES | ARES | HECTARES | SQUARECENTIMETERS | SQUAREDECIMETERS | SQUAREINCHES | SQUAREFEET | SQUAREKILOMETERS | SQUAREMETERS | SQUAREMILES | SQUAREMILLIMETERS | SQUAREYARDS | SQUAREMAPUNITS | UNKNOWN
    • The following are linear units of measure keywords:
      • CENTIMETERS | DECIMALDEGREES | DECIMETERS | FEET | INCHES | KILOMETERS | METERS | MILES | MILLIMETERS | NAUTICALMILES | POINTS | UNKNOWN | YARDS
  • 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 set 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 with enterprise geodatabases:

    • The option is only supported for Db2, Oracle, PostgreSQL, SAP HANA, and SQL Server databases.
    • Calculating field values on joined tables is not supported.
    • Versioned 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.

  • Python 3 —The Python expression type will be used. This is the default.
  • Arcade —The Arcade expression type will be used.
  • SQL —The 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.

  • Text — Any string of characters can be used.
  • Float (single precision) — Fractional numbers between -3.4E38 and 1.2E38 can be used.
  • Double (double precision) — Fractional numbers between -2.2E308 and 1.8E308 can be used.
  • Short (small integer) — Whole numbers between -32,768 and 32,767 can be used.
  • Long (large integer) — Whole numbers between -2,147,483,648 and 2,147,483,647 can be used.
  • Date — Date and time will be used.
  • Blob (binary data) — A long sequence of binary numbers will be used. To load items into a BLOB field or to view the contents, you need a custom loader or viewer or a third-party application.
  • Raster imagery — Raster images will be used. All ArcGIS software-supported raster dataset formats can be stored; however, it is recommended that you use only small images.
  • GUID (globally unique identifier) — A globally unique identifier will 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. 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 set 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.

  • TEXTAny string of characters can be used.
  • FLOAT Fractional numbers between -3.4E38 and 1.2E38 can be used.
  • DOUBLE Fractional numbers between -2.2E308 and 1.8E308 can be used.
  • SHORT Whole numbers between -32,768 and 32,767 can be used.
  • LONG Whole numbers between -2,147,483,648 and 2,147,483,647 can be used.
  • DATEDate and time will be used.
  • BLOBA long sequence of binary numbers will be used.
  • RASTERRaster images will be used. All ArcGIS software-supported raster dataset formats can be stored; however, it is recommended that you use only small images.
  • GUIDA globally unique identifier will 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.AddField_management("vegtable.dbf", "VEG_TYP2", "TEXT", "", "", "20")
arcpy.CalculateField_management("vegtable.dbf", "VEG_TYP2", 
                                '!VEG_TYPE!.split(" ")[-1]', "PYTHON3")
CalculateField example 2 (stand-alone script)

Use CalculateField 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.AddField_management(inFeatures, fieldName1, "DOUBLE", 
                          fieldPrecision, fieldScale)
arcpy.AddField_management(inFeatures, fieldName2, "DOUBLE", 
                          fieldPrecision, fieldScale)
 
# Calculate centroid
arcpy.CalculateField_management(inFeatures, fieldName1, 
                                "!SHAPE.CENTROID.X!",
                                "PYTHON3")
arcpy.CalculateField_management(inFeatures, fieldName2, 
                                "!SHAPE.CENTROID.Y!",
                                "PYTHON3")
CalculateField example 3 (stand-alone script)

Use CalculateField 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"""
 
# Execute AddField
arcpy.AddField_management(inTable, fieldName, "SHORT")
 
# Execute CalculateField 
arcpy.CalculateField_management(inTable, fieldName, expression, "PYTHON3", 
                                codeblock)
CalculateField example 4 (stand-alone script)

Use CalculateField 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"
 
# Execute AddField
arcpy.AddField_management(inFeatures, fieldName, "LONG")
 
# Execute CalculateField 
arcpy.CalculateField_management(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.CalculateField_management("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.CalculateField_management("data", "NEW_VALUE", "SAMPLE * (BASELINE - 40)", "SQL")

Environments

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