2

I have 2 raster datasets of temperature and precipitation from WorldClim. Is there any way to loop through 2 raster datasets at the same time and perform raster calculation on them. So that the combination on every loop is something like this:

temp1 and prec1 
temp2 and prec2
..
temp12 and prec 12

I know how to loop through 1 raster dataset and perform raster calculation on it which looks like this:

import arcpy 
from arcpy.sa import *

arcpy.CheckOutExtension('Spatial')
arcpy.env.workspace = r'D:\Data'
rasters = arcpy.ListRasters('*.tif*')

for raster in rasters:
    outraster = Raster(raster) > 0.1
    #Save temp raster to disk with new name
    outraster.save(raster.replace('.tif', '_temp.tif'))

print('Done Processing')
3

I don"t know exactly what you want to do, but if the names are structured the same way you coul list one input and change its name. It is safer than making two lists if one of the prec%.tif file is missing.

import arcpy 
from arcpy.sa import *

arcpy.CheckOutExtension('Spatial')
arcpy.env.workspace = r'D:\Data'
rasters = arcpy.ListRasters('temp*',"TIF")

for raster in rasters:
    try:
        ras_temp = Raster(raster)
        ras_prec = Raster(raster.replace("temp","prec"))
        #do what you want with the rasters e.g outraster = ras_tem + ras_prec
        #Save temp raster to disk with new name
        outraster.save(raster.replace('.tif','_temp.tif'))
    except:
        print("there was a problem with" + raster)

print('Done Processing')
| improve this answer | |
  • Thanks @radouxju. It worked. Now my only concern is with the outraster.save statement. Instead of the above statement, I would like to save the output rasters in a new folder. That's why I used outraster.save ('D:\Data\result'). But, it didn't execute, probably because I didn't provide any extension or file format. – coder_001 Oct 13 at 13:07
  • yes, something like outraster.save('D:\Data\result\output_' +raster ) should be used. and the directroy must exist. – radouxju Oct 13 at 15:08
5
import arcpy

rasterfolder = r'C:\GIS\data\testdata\outrasters'
arcpy.env.workspace = rasterfolder

temps = arcpy.ListRasters(wild_card='temp*')
precs = arcpy.ListRasters(wild_card='prec*')

for temp, prec in zip(temps, precs):
    print(temp, prec)
    #Do something

Prints:

temp1.tif prec1.tif
temp2.tif prec2.tif

enter image description here

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.