If you have produced a long list of rasters (lets say 50) and want to add them together, is there any shorter way to write in python rather than typing all the inputs, like so:
outRas = inRas1 + inRas2.........+ inRas50
You can make a list of the raster names you wish to add together, then step through the list, adding each one to an output raster.
import arcpy
from arcpy import env
# Set the current workspace
#
env.workspace = "C:/Data/DEMS"
#Check out ArcGIS Spatial Analyst extension license
arcpy.CheckOutExtension("Spatial")
# Get a list of ESRI GRIDs from the workspace and print
#
rasterList = arcpy.ListRasters("*", "GRID")
#Step through the list of raster names
for rasname in rasterList:
#Cast rasname as raster before adding
listras = Raster(rasname)
#Add each raster to an output raster.
#The previous step of casting as a Raster will invoke
#the Spatial Analyst Addition function.
outras += listras
#Save output Raster
outras.save("C:/temp/outras")
rasterList
to exclude any raster you do not want to process.
outras is not defined!
or python hangs!
Another option may just using the python built-in sum
function as below
Step-1:Get list of the paths of the rasters
import arcpy,os
raster_pths = []
for root, dirs, files in os.walk(raster_input_folder):
for single_file in files:
if single_file.endswith('.tif'):
input_raster_pth = os.path.join(root,single_file)
inpt_raster = os.path.join(root, single_file)
raster_pths.append(inpt_raster)
Step-2:Now create a list of arcpy raster using those collected rasters path-it needs memory
needed_rasters_virtual = [arcpy.Raster(i) for i in needed_rasters]
Step-3:Now do the sum
summed_raster = sum(needed_rasters_virtual)
Though the above method needs a lot of memory in case of large raster but it comes handy when you need to do some complex steps at easy go like-
Say you have a value list estimates = [ 0.292088680, -0.000046162, -0.000014440, -0.000023292, -0.000027125, -0.000000819, 0.000032517, -0.000021072, 0.000004663, 0.000047970, 0.000111651, 0.000008808, -0.000014821]
and another raster list,say rsts
of same length. Now you want to multiply each element of the rsts
by respective element of the estimates
list according to their position order and after all you want to get the sum of all of these rasters.I this case this way may comes handy as below-
for the above process:
rsts = [arcpy.Raster(i) for i in needed_rasters]
summed_raster = sum([i*j for i,j in zip(needed_rasters_virtual,estimates)])