Entering values with the keyboard is not the only way you can edit values in a table. In some cases, you might 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.
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 field CITY_NAME.
Strip any white space from the end of the string in the field CITY_NAME.
Replace any occurrences of "california" with "California" found in the field STATE_NAME.
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".
The first character.
The second-to-last character.
The second, third, and fourth characters.
Python also supports string formatting using the format() method.
Combine FieldA and FieldB, separated by a colon.
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.
x + y
x plus y
1.5 + 2.5
x - y
x minus y
3.3 - 2.2
x * y
x times y
2.0 * 2.2
x / y
x divided by y
4.0 / 1.25
x // y
x divided by y (floor division)
4.0 // 1.25
x % y
x modulo y
8 % 3
negative expression of x
x = 5
x is unchanged
x = 5
x ** y
x raised to the power of y
2 ** 3
!Rank! * 2
Calculate volume of a sphere given a radius field.
4.0 / 3.0 * math.pi * !Radius! ** 3
Python built-in functions
Python has a number of built-in functions that are available to use, including max, min, round, and sum.
Calculate the maximum value for each record from a list of fields.
max([!field1!, !field2!, !field3!])
Calculate the sum for each record from a list of fields.
sum([!field1!, !field2!, !field3!])
Using 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.
How the code block is used is determined by the Expression Type parameter. 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, ArcGIS Desktop—Background Geoprocessing (64-bit), and ArcGIS Server. In ArcGIS Pro, the Expression Type parameter is permanently disabled and set to PYTHON_9.3.
|Expression Type||Code Block|
Supports Python functionality. The code block is expressed using Python functions (def). Geometry properties are expressed using geoprocessing objects, such as Point objects, where appropriate.
When using the tool dialog box, the expression type is not shown, but uses the PYTHON_9.3 type.
Same as PYTHON_9.3, but returns strings instead of geometry objects.
Calculations are performed using VBScript.
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 at all). A value is returned from the function using a return statement. The function name is your choice (don't use spaces or leading numbers).
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
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
Calculate the area of a feature.
Calculate the maximum x-coordinate of a feature.
Calculate the vertex count of a feature.
Expression: MySub(!shape!) Code Block: def MySub(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 expressed with an @ sign.
- Areal unit of measure keywords:
- ACRES | ARES | HECTARES | SQUARECENTIMETERS | SQUAREDECIMETERS | SQUAREINCHES | SQUAREFEET | SQUAREKILOMETERS | SQUAREMETERS | SQUAREMILES | SQUAREMILLIMETERS | SQUAREYARDS | SQUAREMAPUNITS | UNKNOWN
- Linear unit of measure keywords:
- CENTIMETERS | DECIMALDEGREES | DECIMETERS | FEET | INCHES | KILOMETERS | METERS | MILES | MILLIMETERS | NAUTICALMILES | POINTS | UNKNOWN | YARDS
Calculate a feature's length in yards.
Calculate a feature's area in acres.
Geodesic area and length can also be calculated using geodesicArea and geodesicLength properties with @ followed by a unit of measure keyword.
Calculate a feature's geodesic length in yards.
Calculate a feature's geodesic area in acres.
Calculate the current date.
Calculate the current date and time.
Calculate the date to be December 31, 2000.
Expression: datetime.datetime(2000, 12, 31)
Calculate the number of days between the current date and the value in a field.
Expression: (datetime.datetime.now() - arcpy.time.ParseDateTimeString(!field1!)).days
Calculate a date by adding 100 days to the date value in a field.
Expression: arcpy.time.ParseDateTimeString(!field1!) + datetime.timedelta(days=100)
Calculate the day of the week (for example, Sunday) for a date value in a field.
Return the three rightmost characters.
Replace any cases of an uppercase P with a lowercase 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(' ')])
The Python re module provides regular expression matching operations that can be used 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
Calculate a sequential ID or number based on an interval.
Expression: autoIncrement() Code Block: rec=0 def autoIncrement(): global rec pStart = 1 #adjust start value, if req'd pInterval = 1 #adjust interval value, if req'd if (rec == 0): rec = pStart else: rec = rec + pInterval 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
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
Calculating null values
Using a Python expression, null values can be calculated using a Python None.
Use a Python None to calculate null values.
Expression: "None" Expression Type: PYTHON_9.3