1

I have two subfolders, which contains rasters for each country but which express different variables. I am trying to figure out a way to Loop a multiplication of each raster into a folder with its pair of the other subfolder. Looks like:.

AFG_13      AFG_25.tif_int     for Afghanistan
AGO_13      AGO_25.tif_int     for Angola
etc...

where the first column rapresents the total population and the second is like a mask (infact I need only the pixel with values 25 converted in the pixel value 1)

In other words I need to multiply AFG_13*con(AFG_25.tif_int==25,1) in Python..I tried already to solve the problem in different ways, but still nothing...some advice?

1

The following requires a Spatial Analyst license.

The ArcPy Raster Object provides a pretty intuitive interface to working with rasters. Once a Raster Object is created, you're allowed to perform math operations on it in a very similar manner to operations on python built-in objects. Properties and methods onboard the Raster Object should also be useful for identifying your rasters in terms of your "AFG" etc. naming convention.

I'd start by making a list of rasters in each of my subfolders, and then iterate through these lists and create raster objects for all rasters. Then, for only those rasters which contain, for example, "AFG" in the name, I would isolate them and perform my math operations. Finally, I'd save the result raster to a permanent file on-disk.

import arcpy
from arcpy.sa import *
import os

country_code = 'AFG_'
variable_code_one = '13'
variable_code_two = '25'
folder_one = 'C:/rasters/folder_one'
folder_two = 'C:/rasters/folder_two'
output_folder = 'C:/rasters/output'
folders_list = [folder_one, folder_two]
raster_objects_list = []

# filter available rasters by country code and create raster objects
for folder in folders_list:
    arcpy.env.workspace = folder
    for raster in arcpy.ListRasters('*' + country_code, 'TIF'):
        raster.split('.')[0] = arcpy.Raster(raster)
        raster_objects_list.append(raster.split('.')[0])

# perform the math operations on the raster objects (this is probably not the best way)
# This assumes there is only 1 "_13" variable raster and only 1 "_25" variable raster available in the set
for raster in raster_objects_list:
    if variable_code_one in raster.name:
        variable_one_raster = raster

for raster in raster_objects_list:
    if variable_code_two in raster.name:
        variable_two_raster = raster

output_raster = (variable_one_raster * variable_two_raster) # or any other math operation
output_raster.save(output_folder + os.sep + country_code + '_results')

Best Luck with this.

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.