ArcPy Add Field and Calculate Field Guide
ArcPy provides powerful tools for adding fields to feature classes and tables, and for calculating field values using Python expressions. This guide covers the essential functions and best practices.
Adding Fields
AddField Function Syntax
python
arcpy.management.AddField(
in_table, # Input table or feature class
field_name, # Name of the field to add
field_type, # Data type (TEXT, LONG, DOUBLE, DATE, etc.)
field_precision, # Optional: Number precision for numeric fields
field_scale, # Optional: Number of decimal places
field_length, # Optional: Maximum length for text fields
field_alias, # Optional: Field alias name
field_is_nullable, # Optional: Whether field can contain null values
field_is_required, # Optional: Whether field is required
field_domain # Optional: Domain to associate with field
)
Common Field Types
- TEXT – Text/string data
- LONG – 32-bit integer
- DOUBLE – Double precision floating point
- FLOAT – Single precision floating point
- SHORT – 16-bit integer
- DATE – Date and time values
- BLOB – Binary large objects
- RASTER – Raster data
Basic Examples
Adding a Single Field
import arcpy
# Add a text field
arcpy.management.AddField("roads", "ROAD_NAME", "TEXT", field_length=50)
# Add a numeric field
arcpy.management.AddField("parcels", "AREA_SQFT", "DOUBLE")
# Add a date field
arcpy.management.AddField("projects", "START_DATE", "DATE")
Adding Multiple Fields in a Loop
import arcpy
# Define field specifications
fields_to_add = [
["Area", "DOUBLE"],
["Longitude", "DOUBLE"],
["Latitude", "DOUBLE"],
["MaxDepth", "DOUBLE"],
["MinDepth", "DOUBLE"]
]
# Add each field
for field_name, field_type in fields_to_add:
arcpy.management.AddField("My_shapefile", field_name, field_type)
AddFields Function (Multiple Fields at Once)
For adding multiple fields efficiently, use the AddFields function:
import arcpy
arcpy.management.AddFields(
'school',
[
['school_name', 'TEXT', 'Name', 255, 'Hello world', ''],
['street_number', 'LONG', 'Street Number', None, 35, 'StreetNumDomain'],
['year_start', 'DATE', 'Year Start', None, '2017-08-09 16:05:07', '']
]
)
Calculating Field Values
CalculateField Function Syntax
arcpy.management.CalculateField(
in_table, # Input table or feature class
field, # Field to calculate
expression, # Calculation expression
expression_type, # Optional: "PYTHON3", "ARCADE", or "VB" (legacy)
code_block, # Optional: Python code block for complex calculations
field_type, # Optional: Field data type
enforce_domains # Optional: Whether to enforce domain rules
)
Field Reference Syntax
Python Expressions
- Field references: Use exclamation points
!fieldname! - Geometry properties:
!shape.area!,!shape.length!,!shape@area! - Example:
!POPULATION! * 2
Arcade Expressions
- Field references: Use
$feature.fieldname - Example:
$feature.POPULATION * 2
Basic Calculation Examples
Simple Mathematical Operations
import arcpy
# Multiply field values by 2
arcpy.management.CalculateField("parcels", "AREA_DOUBLED", "!AREA! * 2", "PYTHON3")
# Calculate area in square kilometers
arcpy.management.CalculateField(
"polygons",
"AREA_SQKM",
"!shape.area@squarekilometers!",
"PYTHON3"
)
# Concatenate text fields
arcpy.management.CalculateField(
"addresses",
"FULL_ADDRESS",
"!STREET_NUM! + ' ' + !STREET_NAME!",
"PYTHON3"
)
Using Geometry Properties
# Calculate polygon area
arcpy.management.CalculateField("parcels", "AREA", "!shape.area!", "PYTHON3")
# Calculate line length
arcpy.management.CalculateField("roads", "LENGTH", "!shape.length!", "PYTHON3")
# Get centroid coordinates
arcpy.management.CalculateField("parcels", "CENTROID_X", "!shape.centroid.X!", "PYTHON3")
arcpy.management.CalculateField("parcels", "CENTROID_Y", "!shape.centroid.Y!", "PYTHON3")
Advanced Calculations with Code Blocks
For complex calculations, use the code_block parameter:
import arcpy
# Define a function in code block
code_block = """
def calculate_grade(score):
if score >= 90:
return 'A'
elif score >= 80:
return 'B'
elif score >= 70:
return 'C'
elif score >= 60:
return 'D'
else:
return 'F'
"""
arcpy.management.CalculateField(
"students",
"GRADE",
"calculate_grade(!TEST_SCORE!)",
"PYTHON3",
code_block
)
Conditional Calculations
Using Python Conditional Expressions
# Simple conditional
arcpy.management.CalculateField(
"parcels",
"SIZE_CLASS",
"'Large' if !AREA! > 5000 else 'Small'",
"PYTHON3"
)
# Multiple conditions
expression = """
'High' if !POPULATION! > 50000
else 'Medium' if !POPULATION! > 10000
else 'Low'
"""
arcpy.management.CalculateField("cities", "POP_CLASS", expression, "PYTHON3")
Complete Workflow Example
Here’s a complete example that adds fields and calculates values:
import arcpy
# Set workspace
arcpy.env.workspace = r"C:\data\myproject.gdb"
# Input feature class
fc = "parcels"
try:
# Add new fields
print("Adding fields...")
arcpy.management.AddField(fc, "AREA_SQFT", "DOUBLE")
arcpy.management.AddField(fc, "AREA_ACRES", "DOUBLE")
arcpy.management.AddField(fc, "SIZE_CLASS", "TEXT", field_length=10)
# Calculate area in square feet
print("Calculating area in square feet...")
arcpy.management.CalculateField(fc, "AREA_SQFT", "!shape.area!", "PYTHON3")
# Calculate area in acres (1 acre = 43,560 sq ft)
print("Calculating area in acres...")
arcpy.management.CalculateField(fc, "AREA_ACRES", "!AREA_SQFT! / 43560", "PYTHON3")
# Classify parcels by size
print("Classifying parcel sizes...")
size_expression = """
'Large' if !AREA_ACRES! > 5
else 'Medium' if !AREA_ACRES! > 1
else 'Small'
"""
arcpy.management.CalculateField(fc, "SIZE_CLASS", size_expression, "PYTHON3")
print("Field calculations completed successfully!")
except arcpy.ExecuteError:
print(f"Error: {arcpy.GetMessages()}")
Best Practices
Performance Tips
- Use AddFields for multiple fields – More efficient than multiple AddField calls
- Work with in-memory data when possible for better performance
- Use appropriate field types – Don’t use TEXT for numeric data
- Consider field length for TEXT fields to optimize storage
Error Handling
import arcpy
def safe_add_field(table, field_name, field_type, **kwargs):
"""Safely add field with error handling"""
try:
# Check if field already exists
existing_fields = [f.name for f in arcpy.ListFields(table)]
if field_name not in existing_fields:
arcpy.management.AddField(table, field_name, field_type, **kwargs)
print(f"Added field: {field_name}")
else:
print(f"Field {field_name} already exists")
except arcpy.ExecuteError:
print(f"Error adding field {field_name}: {arcpy.GetMessages()}")
# Usage
safe_add_field("parcels", "NEW_FIELD", "DOUBLE")
Field Naming Conventions
- Use descriptive names:
POPULATION_2020notPOP20 - Avoid spaces and special characters
- Use underscores for word separation
- Keep names under 64 characters for compatibility
- Use consistent naming patterns across your project
Common Issues and Solutions
Issue: “Field already exists”
Solution: Check existing fields first
existing_fields = [f.name for f in arcpy.ListFields(table)]
if field_name not in existing_fields:
arcpy.management.AddField(table, field_name, field_type)
Issue: Calculation errors with null values
Solution: Handle nulls in expressions
expression = "0 if !FIELD! is None else !FIELD! * 2"
Issue: Text concatenation with nulls
Solution: Use conditional logic
expression = "str(!FIELD1!) + ' - ' + str(!FIELD2!) if !FIELD1! and !FIELD2! else ''"
This guide covers the essential aspects of adding fields and calculating values with ArcPy. These tools are fundamental for data processing and analysis workflows in ArcGIS.