HOW TO

Perform raster calculation using ArcPy

Last Published: July 19, 2023

Summary

The Spatial Analyst tools can be executed using the Spatial Analyst ArcPy module to perform raster analysis. When writing a Python script, it is possible to drag and drop a tool into the Python console to generate a line of code. Although the line of code is generated for the Raster Calculator tool, the execution returns an empty output, or fails with the following error message:

Error:   
AttributeError: module 'arcpy.sa' has no attribute 'RasterCalculator' 
The Raster Calculator tool is not intended for use in scripting environments and is not available in the standard Spatial Analyst ArcPy module. It is designed for use only in the application as a geoprocessing tool or in ModelBuilder. However, it is possible to deploy the Spatial Analyst Arcpy module for use with Map Algebra operators in Python scripting. Refer to ArcGIS Pro: Working with operators in Map Algebra for more information.

Procedure

The sample script below represents the workflow to modify pixel values using the multiplication operation on all the rasters in a folder.

  1. Import the necessary module.
import arcpy
from arcpy import env
from arcpy.sa import *
  1. Specify the desired workspace.
arcpy.env.workspace = r"<location_path>\<name>.gdb"

arcpy.env.scratchWorkspace = r"<location_path>\<name>.gdb"
  1. Print the list of available raster files in the folder.
raster_list = arcpy.ListRasters("*")
print (raster_list)
  1. Check out the Spatial Analyst extension.
try:
    if arcpy.CheckExtension("Spatial") == "Available":
        arcpy.CheckOutExtension("Spatial")
        print ("Checked out \"Spatial\" Extension")
    else:
        raise LicenseError
except LicenseError:
    print "Spatial Analyst license is unavailable"
except:
    print arcpy.GetMessages(2)
  1. Loop through all the raster files, perform the calculation, and specify the desired save folder.
for raster in raster_list:
    ras = Raster(raster)
    filename = str(raster)[:-3] + '<desired file extension>'
    outraster = ras * <desired_value>          
    outraster.save(r"<location_path>\<name>.gdb" + "\\" + filename)

Article ID:000022418

Software:
  • ArcGIS Pro
  • ArcMap

Get help from ArcGIS experts

Contact technical support

Download the Esri Support App

Go to download options

Related Information

Discover more on this topic