Calculate Field Python examples

Entering values using the keyboard is not the only way you can edit values in a table. You may want to perform a mathematical calculation to set a field value for a single record or even all records. You can perform simple as well as advanced calculations on all or selected records. In addition, you can calculate area, length, perimeter, and other geometric properties on fields in attribute tables. The sections below include examples of using the field calculator. Calculations are performed using Python, SQL, and Arcade.

This topic focuses on Python-based Calculate Field examples. To learn more about Arcade expressions, see the ArcGIS Arcade guide. To learn more about SQL expressions, see Calculate field values. To learn more about VBScript examples, see Calculate Field VBScript examples.

Note:
  • Python enforces indentation as part of the syntax. Use two or four spaces to define each logical level. Align the beginning and end of statement blocks, and be consistent.
  • Python calculation expression fields are enclosed with exclamation points (!!).
  • When naming variables, note that Python is case sensitive, so value is not the same as Value.
  • After entering statements, click the Export button Export if you want to write them to a file. The Import button Import prompts you to find and select an existing calculation file.

Simple calculations

A variety of calculations can be calculated with only a short expression.

Simple string examples

Strings are supported by a series of Python string functions, including capitalize, rstrip, and replace.

Capitalize the first character of the string in the CITY_NAME field.

!CITY_NAME!.capitalize()

Remove any space from the end of the string in the CITY_NAME field.

!CITY_NAME!.rstrip()

Replace any occurrences of "california" with "California" in the STATE_NAME field.

!STATE_NAME!.replace("california", "California")

Characters in a string field can be accessed by indexing and slicing in Python. Indexing fetches characters at an index position; slicing fetches a group of characters. In the following table, assume that !fieldname! is a string field with a value of "abcde".

ExampleExplanationResult

!fieldname![0]

The first character

"a"

!fieldname![-2]

The second-to-last character

"d"

!fieldname![1:4]

The second, third, and fourth characters

"bcd"

Python also supports string formatting using the format() method.

Combine FieldA and FieldB, separated by a colon.

"{}:{}".format(!FieldA!, !FieldB!)

Simple math examples

Python provides tools for processing numbers. Python also supports a number of numeric and mathematical functions, including math, cmath, decimal, random, itertools, functools, and operator.

OperatorExplanationExampleResult

x + y

x plus y

1.5 + 2.5

4.0

x - y

x minus y

3.3 - 2.2

1.1

x * y

x times y

2.0 * 2.2

4.4

x / y

x divided by y

4.0 / 1.25

3.2

x // y

x divided by y (floor division)

4.0 // 1.25

3.0

x % y

x modulo y

8 % 3

2

-x

negative expression of x

x = 5

-x

-5

+x

x is unchanged

x = 5

+x

5

x ** y

x raised to the power of y

2 ** 3

8

Multiply the values of a field by 2.

!Rank! * 2

Calculate volume of a sphere given a radius field.

4.0 / 3.0 * math.pi * !Radius! ** 3
Note:

Short, Long, and Big Integer fields differ in the following ranges of whole numbers they support:

  • Short (16-bit integer)—Support whole numbers from -(215) and 215 (-32,768 and 32,767)
  • Long (32-bit integer)—Support whole numbers from -(231) and 231 (-2,147,483,648 and 2,147,483,647)
  • Big Integer (64-bit integer)—Support whole numbers from -(253) and 253 (-9,007,199,254,740,992 and 9,007,199,254,740,991)

Legacy:

In ArcGIS Pro, Python 3 is used, and in ArcGIS Desktop, Python 2 is used. Python 2 uses integer math, meaning that dividing two integer values always produces an integer value (3 / 2 = 1). In Python 3, dividing two integer values produces a float value (3 / 2 = 1.5).

Python built-in functions

Python includes a number of built-in functions, including max, min, round, and sum.

Calculate the maximum value for each record from a list of fields.

Expression:
max([!field1!, !field2!, !field3!])

Calculate the sum for each record from a list of fields.

Expression:
sum([!field1!, !field2!, !field3!])

Use code blocks

With Python expressions and the Code Block parameter, you can do the following:

  • Use any Python function in the expression.
  • Access geoprocessing functions and objects.
  • Access properties of feature geometry.
  • Access the new random value operator.
  • Reclassify values using if-then-else logic.

Expression typeCode block

Python (PYTHON3 keyword)

Supports Python functionality. The code block is expressed using Python functions (def). Geometry properties are expressed using geoprocessing objects, such as Point objects, when appropriate.

Arcade

Supports Arcade functionality.

SQL

Supports SQL expressions.

SQL expressions were implemented to better support calculations using feature services and enterprise geodatabases, particularly regarding performance. Instead of performing calculations one feature or row at a time, a single request is sent to the feature service or database.

Legacy:

In ArcGIS Desktop, the Calculate Field tool supports VB, PYTHON, and PYTHON_9.3 expression types. The VB expression type, which is supported in some products, is not supported on 64-bit products, including ArcGIS Pro.

PYTHON and PYTHON_9.3 keywords are still supported in ArcGIS Pro for backward compatibility but are not listed as choices. Python scripts that use these keywords will continue to work.

The only difference between the PYTHON3 expression type and the legacy PYTHON_9.3 keyword is that PYTHON3 returns the values in date fields as Python datetime objects.

Note:

The PYTHON3 expression type is not related to the version of Python installed with ArcGIS Pro. It is the third Python-related keyword historically (after the now hidden PYTHON and PYTHON_9.3 keywords).

Python functions are defined using the def keyword followed by the name of the function and the function’s input arguments. A Python function can be written to accept any number of input arguments (including none). A value is returned from the function using a return statement. The function name is your choice (don't use spaces or leading numbers).

Note:

If a value is not explicitly returned from a function with a return statement, the function returns None.

Note:

Python enforces indentation as part of the syntax. Use four spaces to define each logical level. Align the beginning and end of statement blocks, and be consistent.

Code samples—math

Simple mathematical expressions can be added using the Expression parameter and more complex examples can be built using the Expression and Code Block parameters.

Round a field's value to two decimal places.

Expression:
round(!area!, 2)

Use the math module to help convert meters to feet. The conversion is raised to the power of 2 and multiplied by the area.

Expression:
MetersToFeet((float(!shape.area!)))

Code Block:
import math
def MetersToFeet(area):
    return math.pow(3.2808, 2) * area

Calculate fields using logic with Python

Logical patterns can be included in a code block using if, else, and elif statements.

Classify based on field values.

Expression:
Reclass(!WELL_YIELD!)

Code Block:
def Reclass(WellYield):
    if (WellYield >= 0 and WellYield <= 10):
        return 1
    elif (WellYield > 10 and WellYield <= 20):
        return 2
    elif (WellYield > 20 and WellYield <= 30):
        return 3
    elif (WellYield > 30):
        return 4

Code samples—geometry

In addition to the following code samples, see the Geometry unit conversions section below for more information about converting geometry units.

Calculate the area of a feature.

Expression:
!shape.area!

Calculate the maximum x-coordinate of a feature.

Expression:
!shape.extent.XMax!

Calculate the vertex count of a feature.

Expression:
getVertexCount(!shape!)

Code Block:
def getVertexCount(feat):    
    partnum = 0

    # Count the number of points in the current multipart feature
    partcount = feat.partCount
    pntcount = 0

    # Enter while loop for each part in the feature (if a singlepart 
    # feature, this will occur only once)
    while partnum < partcount:
        part = feat.getPart(partnum)
        pnt = part.next()

        # Enter while loop for each vertex
        while pnt:
            pntcount += 1   
            pnt = part.next()
   
            # If pnt is null, either the part is finished or there 
            # is an interior ring
            if not pnt: 
                pnt = part.next()
        partnum += 1
    return pntcount

For a point feature class, shift the x-coordinate of each point by 100.

Expression:
shiftXCoordinate(!SHAPE!)

Code Block:
def shiftXCoordinate(shape):
    shiftValue = 100
    point = shape.getPart(0)
    point.X += shiftValue
    return point

Geometry unit conversions

Area and length properties of the geometry field can be modified with unit types using the getArea and getLength geometry methods.

Learn more about supported linear and areal units in geoprocessing

See the Polygon and Polyline objects for more information.

Caution:

Converting the areal units on data in a geographic coordinate system produces questionable results since decimal degrees are not consistent across the globe.

Calculate a feature's length in yards.

Expression:
!shape@getLength('PLANAR', 'YARDS')

Calculate a feature's area in acres.

Expression:
!shape@getArea('PLANAR', 'ACRES')

Geodesic area and length can also be calculated using the GEODESIC method type.

See Polygon and Polyline objects for more information.

Learn more about geoprocessing tools and linear and areal units

Calculate a feature's geodesic length in yards.

Expression:
!shape@getLength('GEODESIC', 'YARDS')

Calculate a feature's geodesic area in acres.

Expression:
!shape@getArea('GEODESIC', 'ACRES')

Code samples—date fields

Date and time can be calculated using the datetime and time modules.

Calculate the current date.

Expression:
time.strftime("%d/%m/%Y")

Calculate the current date and time.

Expression:
datetime.now()

Calculate the date to be March 15, 2015, 1:30:00 pm.

Expression:
datetime(year=2015, month=3, day=15, hour=13, minute=30, second=0))

Calculate the number of days between the current date and the value in a field.

Expression:
datetime.now().day - !OID!

Calculate a date by adding 100 days to the date value in a field.

Expression:
!field1! + timedelta(days=100)

Code Block:
from datetime import timedelta

Calculate a string representing the date using the ctime method in the datetime module. The example creates a string in the format: 'Mon Feb 22 10:15:00 2021'.

Expression:
!field1!.ctime()

Calculate the day of the week (for example, Sunday) for a date value in a field.

Expression:
!field1!.strftime('%A')

Calculate a formatted string from a date field using the datetime module's strftime method and an explicit format string. The example will create a string in the format: '02/22/2021, 10:15:00'.

Expression:
!field1!.strftime("%m/%d/%Y, %H:%M:%S")

Calculate a date using an ISO 8601 formatted string.

Expression:
'1969-07-21 02:56:00'

Calculate a date using month, day, year, time convention.

Expression:
'July 1 2020 12:30:45'

Code samples—time only fields

Calculate the time to be 4:30:00 pm using the datetime module's time function.

Expression:
time(hour=16, minute=30, second=0)

Code Block:
from datetime import time

Calculating a date field to a time only field will apply only the time portion of the datetime object.

Expression:
!date_field!

Code samples—date only fields

Calculate the date to be December 31, 2000.

Expression:
datetime(2000, 12, 31)

Calculating a date field to a time only field will apply only the time portion of the datetime object.

Expression:
!date_field!

Code samples—timestamp offset fields

Add a UTC timestamp offset to the current date and time using the datetime.timezone module's utc property.

Expression:
datetime.now(tz=timezone.utc)

Code Block:
from datetime import timezone

Add a timestamp offset to the current date and time using the zoneinfo module's ZoneInfo class to set the time zone.

Expression:
datetime.now(ZoneInfo('America/New_York'))

Code Block:
from zoneinfo import ZoneInfo

Code samples—strings

String calculations can be completed using a variety of Python coding patterns.

Return the three rightmost characters.

Expression:
!SUB_REGION![-3:]

Replace any cases of an uppercase P with a lowercase p.

Expression:
!STATE_NAME!.replace("P","p")

Concatenate two fields with a space separator.

Expression:
!SUB_REGION! + " " + !STATE_ABBR!

Convert to proper case

The following examples show different ways to convert words so that each word has the first character capitalized and the rest of the letters in lowercase.

Expression:
' '.join([i.capitalize() for i in !STATE_NAME!.split(' ')])
Expression:
!STATE_NAME!.title()

Regular expressions

The Python re module provides regular expression matching operations that you can use to perform complex pattern matching and replacement rules for strings.

Replace St or St. starting a new word at the end of the string with the word Street.

Expression:
update_street(!ADDRESS!)

Code Block:
import re
def update_street(street_name):
    return re.sub(r"""\b(St|St.)\Z""",  
                  'Street',
                  street_name)

Accumulative and sequential calculations

Accumulative and sequential calculations can be performed using global variables.

Calculate a sequential ID or number based on an interval.

Expression:
autoIncrement(10, 5)

Code Block:
rec = 0
def autoIncrement(start=1, interval=1):
    global rec
    if rec == 0:
        rec = start
    else:
        rec += interval
    return rec

Calculate the accumulative value of a numeric field.

Expression:
accumulate(!FieldA!)

Code Block:
total = 0
def accumulate(increment):
    global total
    if total:
        total += increment
    else:
        total = increment
    return total

Calculate the percentage increase of a numeric field.

Expression:
percentIncrease(float(!FieldA!))

Code Block:
lastValue = 0
def percentIncrease(newValue):
    global lastValue
    if lastValue:
        percentage = ((newValue - lastValue) / lastValue)  * 100
    else: 
        percentage = 0
    lastValue = newValue
    return percentage

Random values

Random values can be calculated using the random module.

Use the numpy site package to calculate random float values between 0.0 and 1.0.

Expression:
getRandomValue()

Code Block:
import numpy

def getRandomValue():
    return numpy.random.random()

Use the random module to calculate random integers between 0 and 10.

Expression:
random.randint(0, 10)

Code Block:
import random

Calculate null values

In a Python expression, null values can be calculated using a Python None.

Note:

The following calculation only works if the field is nullable.

Use a Python None to calculate null values.

Expression:
None

Related topics