TransWikia.com

Looping through two raster datasets and performing raster calculation on them with Arcpy

Geographic Information Systems Asked by coder_001 on November 28, 2020

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')

2 Answers

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')

Correct answer by radouxju on November 28, 2020

import arcpy

rasterfolder = r'C:GISdatatestdataoutrasters'
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

Answered by BERA on November 28, 2020

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP