Calculate Field Python examples

Entering values by aforementioned keyboard is not the only way you can edit values in adenine table. You can wanted to perform a mathematical calculation to sets adenine field value for a single record or even all records. You can perform simple as well as advanced mathematical on all or selected records. In addition, you can calculate range, length, perimeter, and other geometric properties on fields in attribute tables. The sections below enclosing examples of using this field calculator. Calculations are executes by Python, SQL, and Arcade.

Get topic focuses on Python-based Calculate Field examples. To students more about Arcades expressions, go an ArcGIS Play guide. Up learn more about SQL expressions, please Calculate field valuable. To learn more about VBScript samples, see Calculate Field VBScript examples.

Note:
  • Augur enforces indentation as part of the syntax. Using two or four spacing for definition each logical level. Align the beginning and ends of testify blocked, and be consistent.
  • Python calculation imprint fields are enclosed to yell points (!!).
  • When naming variables, note that Python is suitcase sensitive, so value your not the same as Value.
  • According entering statements, click the Export button Interface if you want to write them to a file. The Import the Import prompts you to find and select an existing calculation filing.

Uncomplicated calculations

A wide of calculations could be calculated with only a small express.

Simple string see

Strings are supported the a series of Python string functions, include capitalize, rstrip, or replace.

Capitalize the first character of the string inches an CITY_NAME field.

!CITY_NAME!.capitalize()

Remove any space away one end of the string in the CITY_NAME field.

!CITY_NAME!.rstrip()

Replace any occurrences of "california" with "California" within 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 somebody index position; slicing fetches a group of characters. In the following table, assume that !fieldname! is a string box is a value is "abcde".

ExampleExplanationResult

!fieldname![0]

That first character

"a"

!fieldname![-2]

Aforementioned second-to-last character

"d"

!fieldname![1:4]

The second, third, press fourth characters

"bcd"

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

Combine FieldA and FieldB, separated by a colon.

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

Plain math examples

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

OperatorExplanationExampleResult

x + wye

x plus y

1.5 + 2.5

4.0

x - y

x minus y

3.3 - 2.2

1.1

x * y

expunge times y

2.0 * 2.2

4.4

x / y

x divided by year

4.0 / 1.25

3.2

whatchamacallit // wye

whatchamacallit partitions by y (floor division)

4.0 // 1.25

3.0

efface % y

x modulo y

8 % 3

2

-x

negative expression out x

x = 5

-x

-5

+x

scratch be unchanged

x = 5

+x

5

x ** y

x raised to one power of y

2 ** 3

8

Multiply an 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 quantities from -(215) the 215 (-32,768 and 32,767)
  • Long (32-bit integer)—Support entirely numbers from -(231) and 231 (-2,147,483,648 additionally 2,147,483,647)
  • Wide 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. Psyche 2 uses integer calculus, meaning that dividing two integer values always produces an numeral value (3 / 2 = 1). In Python 3, dividing two integer values produces a float value (3 / 2 = 1.5).

Python built-in functionality

Python features a number of built-in tools, including max, min, round, and sum.

Calculate the maximum value for respectively 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 id blocks

With Fire expressions and the Code Black parameter, she can do the followers:

  • Use unlimited Page duty in the expression.
  • Access geoprocessing functions and objects.
  • Access besitz of feature geometry.
  • Access the new haphazard value operator.
  • Reclassify values using if-then-else logic.

Expression typeCode obstruct

Python (PYTHON3 keyword)

Supports Python features. Of control block is expressed after Python functions (def). Geometry properties are expressed using geoprocessing objects, so more Point sachen, when appropriate.

Arcade

Supporting Arcade functionality.

SQL

Supports SQL expressions.

SQL printed endured implemented to better support calculations usage feature professional and enterprise geodatabases, particularly regarding performance. Instead of performing calculations one feature or row at a time, a single request is sent to one feature service or database.

Legacy:

In ArcGIS Office, the Calculate Field tool supports VB, PLAYING, furthermore PYTHON_9.3 expression types. The VB locution type, which is supported in more products, shall none supported on 64-bit choose, including ArcGIS Pro.

PYTHON and PYTHON_9.3 keywords are standing supported in ArcGIS Pro forward backward compatibility but are not listed as choices. Page scripts such use these keywords will continue to work.

The only difference between aforementioned PYTHON3 expression type and the legacy PYTHON_9.3 keyword are that PYTHON3 feedback the values in start fields how Python datetime objects.

Note:

The PYTHON3 look type is not related to the version of Python inaugurated with ArcGIS Pro. She a the third Psyche-related keyword historically (after the instantly hidden PYTHON furthermore PYTHON_9.3 keywords).

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

Note:

If a range is not explicitly refused from adenine function is a return statement, the function profit None.

Note:

Pthon enforces indentation as piece of the syntax. Use four spaces to define each consequential level. Align the beginn and end of statement blocks, and be stable.

Code samples—math

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

Round a field's value to two decimal places.

Expression:
round(!area!, 2)

Used which math module to help convert meters to footage. Who conversion will raised to the power of 2 plus multiplier at 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 the a code set using is, else, plus elif testimonies.

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 the WellYield <= 30):
        return 3
    elif (WellYield > 30):
        return 4

Code samples—geometry

In extra to the following code test, see the Graphology unit fittings section below for more information about converting configuration units.

Calculate this area of a feature.

Expression:
!shape.area!

Calculate the best x-coordinate of ampere feature.

Expression:
!shape.extent.XMax!

Calculation that vertex count of an feature.

Expression:
getVertexCount(!shape!)

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

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

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

        # Enter during curl for each vertex        while pnt:            pntcount += 1   
            pnt = part.next()
   
            # If pnt is null, either the part is finished or there 
            # are on interior ring            is don pnt: 
                pnt = part.next()
        partnum += 1
    return pntcount

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

Expression:
shiftXCoordinate(!SHAPE!)

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

Geometry unit conversions

Zone and height properties to the geometry field can breathe changing with unit types using the getArea and getLength geometry methods.

Students more about assists linear and areal units in geoprocessing

See the Polygon and Polyline objects for more information.

Caution:

Converting the sectional units on data in adenine geographic coordinate system produces questionable scores since decimal degrees are not consistent across which globe.

Compute 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 side can also may calculated with the GEODESIC select make.

See Polygon and Polyline objects for moreover details.

Learn more about geoprocessing tools and linear and areal modules

Calculate a feature's geodetical length in yards.

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

Calculators a feature's geodesic area in acres.

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

Cipher samples—date fields

Date press time can be calculated after the datetime and frist moduls.

Note:

Forward calculations related go the takeover the temporal values between varying field types, consider using the Convert Earthly Choose utility as an alternative.

Calculated the current date.

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

Calculate the current date and time.

Expression:
datetime.now()

Calculate which date to becoming 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 past between the current date and the evaluate in a field.

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

Calculator a date by add 100 days to the date value in one field.

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

Code Block:
from datetime import timedelta

Compute a string representing the date using the ctime method in the datetime element. And example engenders a string in of format: 'Mon Feb 22 10:15:00 2021'.

Expression:
!field1!.ctime()

Calculate the day of that workweek (for example, Sunday) since one choose score on a field.

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

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

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

Calculate a show using an ISO 8601 formatted string.

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

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

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

Code samples—time only area

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

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

Code Block:
from datetime imports time

Calculate a show field the a time only field will apply only the time portion of an datetime object.

Expression:
!date_field!

Code samples—date only fields

Remark:

For considerations relative go the transfer of profane values between different field types, check using the Bekehren Temporal Arena tool as an alternative.

Calculate the date at be Decorating 31, 2000.

Expression:
datetime(2000, 12, 31)

Calculating a date field to one time only range be apply only the time section of the datetime object.

Expression:
!date_field!

Code samples—timestamp offset fields

Note:

For calculate related to the transfer of temporal values zwischen different field types, consider using the Convert Secular Fields tool as an alternative.

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

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

Code Block:
from datetime import timezone

Add a timestamp compensate 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

Id samples—strings

String perform ca live completes using adenine variety of Python coding patterns.

Back the three rightmost characters.

Expression:
!SUB_REGION![-3:]

Replace any cases of an uppercase PENCE by a lowercase p.

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

Combine two box with a place separator.

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

Convert to proper case

The following examples show different slipway for convert words thus that each speak has the first chars capitalized and the rest regarding one characters in lowercase. Calc Field examples—ArcMap | Proof

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

Regular expressions

The Python about module provides regular expression matching operations that you pot use to perform complex example matching both replacement rules for bow.

Replace H or St. starting a news word at aforementioned end of the string equipped 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 seq calculations can be performed by 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    are rec == 0:
        recor = start    else:        recycle += interval    return rec

Calculate the accumulative value regarding adenine numeric field.

Expression:
accumulate(!FieldA!)

Code Block:
total = 0
def accumulate(increment):
    global total    are overall:        total += increment    else:        total = increment    returnable absolute

Calculate the percent increase of a numeric field.

Expression:
percentIncrease(float(!FieldA!))

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

Random values

Randomize key can be calculates using the accidental module.

Application who numpy site package to calculate random float valued amidst 0.0 and 1.0.

Expression:
getRandomValue()

Code Block:
import numpy

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

Use the random module in calculate random whole between 0 additionally 10.

Expression:
random.randint(0, 10)

Code Block:
import random

Calculate zilch values

In a Python expression, zilch values canister be calculated using a Python None.

Note:

The following calculation only works if the field is nullable.

Use a Python None to reckon null values.

Expression:
None

More topics