calculate mean of selected raster chosen from multiple raster using ArcPy

2915
52
Jump to solution
08-24-2016 11:15 AM
ShouvikJha
Occasional Contributor III

I am trying to  calculate mean of selected raster chosen from multiple raster. I have multiple raster file in different month folder, i am trying to select only two raster (e.g For JANUARY : 001_Max_Temper.tif, 001_Min_Temper.tif) from different month folder (JANUARY, FEBRUARY....DECEMBER) and calculate the mean of those selected raster and save it as on same month folder (e.g output name, JANUARY: 001_Mean_Temp). 

I have written a code to do this task but i am getting error massage while i am running this code. Below i have attached my code.  

import arcpy, os, calendar
from arcpy import env
from arcpy.sa import *
arcpy.CheckOutExtension("Spatial")
arcpy.env.parallelProcessingFactor = "100%"
topWorkspace = r'D:\SWAT-WEATHER-DATA2'
arcpy.env.workspace = topWorkspace

# Get dict of months and month-number (i.e. January = 001, March = 003 etc.)
months = {calendar.month_name[i].upper(): str(i).zfill(3) for i in range(1, 13)} # Get dict of months and month number (i.e. January = 001, March = 003 etc.)

# Step through list of all folders
for folderPath in arcpy.ListWorkspaces():
    baseName = os.path.basename(folderPath).upper()
    if baseName in months: # Test that subfolder is a month name
        monthNumber = months[baseName] # Get month-number for use in output filename
        arcpy.env.workspace = folderPath
        rasterList = arcpy.ListRasters('*Max_Temper.tif', '*Min_Temper.tif')
        # Execute CellStatistics
        outCellStatistics = CellStatistics(rasterList, "MEAN", "NODATA")
        #Save the output
        outRasterName = outCellStatistics, "Mean_Temp_{}.tif".format(monthNumber)
        outCellStatistics.save(outRasterName)
        

#print done
print 'done'
Tags (2)
0 Kudos
1 Solution

Accepted Solutions
XanderBakker
Esri Esteemed Contributor

... or to be more specific, something like this:

import arcpy, os, calendar
from arcpy.sa import *
arcpy.CheckOutExtension("Spatial")
arcpy.env.parallelProcessingFactor = "100%"
topWorkspace = r'D:\SWAT-WEATHER-DATA2'
ws_out = r'D:\SWAT-WEATHER-DATA2\MeanRasters' ### create this folder!!!
arcpy.env.workspace = topWorkspace

# Get dict of months and month-number (i.e. January = 001, March = 003 etc.)
months = {calendar.month_name[i].upper(): str(i).zfill(3) for i in range(1, 13)} # Get dict of months and month number (i.e. January = 001, March = 003 etc.)


# Step through list of all folders
for folderPath in arcpy.ListWorkspaces():
    baseName = os.path.basename(folderPath).upper()
    if baseName in months: # Test that subfolder is a month name
        monthNumber = months[baseName] # Get month-number for use in output filename
        arcpy.env.workspace = folderPath

        # list rasters
        rasterList1 = arcpy.ListRasters('*Max_Temper.tif')
        rasterList2 = arcpy.ListRasters('*Min_Temper.tif')

        # combine lists
        rasterList = rasterList1 + rasterList2

        # Execute CellStatistics
        outCellStatistics = CellStatistics(rasterList, "MEAN", "NODATA")

        #Save the output
        outRasterName = os.path.join(ws_out, "Mean_Temp_{}.tif".format(monthNumber))
        outCellStatistics.save(outRasterName)

#print done
print 'done'

View solution in original post

52 Replies
DarrenWiens2
MVP Honored Contributor

What/where is the error?

ShouvikJha
Occasional Contributor III

the following error massage i am getting 

Message File Name Line Position 
Traceback 
 <module> <module1> 20 
 CellStatistics C:\Program Files\ArcGIS\Desktop10.1\arcpy\arcpy\sa\Functions.py 2817 
 swapper C:\Program Files\ArcGIS\Desktop10.1\arcpy\arcpy\sa\Utils.py 47 
 wrapper C:\Program Files\ArcGIS\Desktop10.1\arcpy\arcpy\sa\Functions.py 2813 
RuntimeError: ERROR 999998: Unexpected Error. 
0 Kudos
XanderBakker
Esri Esteemed Contributor

There are a number of errors in the code. The generation of the "months" dictionary is well defined, but keep in mind that the folder names should be in the language of what is defined in the regional settings. In my case it returns in Spanish:

{'JULIO': '007', 'SEPTIEMBRE': '009', 'MARZO': '003', 'JUNIO': '006', 'ABRIL': '004', 'ENERO': '001', 'AGOSTO': '008', 'FEBRERO': '002', 'DICIEMBRE': '012', 'NOVIEMBRE': '011', 'MAYO': '005', 'OCTUBRE': '010'}

The line:

rasterList = arcpy.ListRasters('*Max_Temper.tif', '*Min_Temper.tif')

Will not work, since "arcpy.ListRasters" allows two parameters; the first is the wildcard, the second is the raster type. You are specifying two wildcards. You can either use:

rasterList = arcpy.ListRasters('*_Temper.tif')

... or create two lists and combine them.

The other line where the code will produce an error is:

outRasterName = outCellStatistics, "Mean_Temp_{}.tif".format(monthNumber)

outCellStatistics is a raster object. You will have to use something like (ws_out is your output workspace, and needs to be defined before):

outRasterName = os,.path.join(ws_out, "Mean_Temp_{}.tif".format(monthNumber))

ShouvikJha
Occasional Contributor III

Xander Bakker‌ . i have corrected the code, but still error.  month folder name in my database is (JANUARY, FEBRUARY ....DECEMBER)

import arcpy, os, calendar
from arcpy import env
from arcpy.sa import *
arcpy.CheckOutExtension("Spatial")
arcpy.env.parallelProcessingFactor = "100%"
topWorkspace = r'D:\SWAT-WEATHER-DATA2'
arcpy.env.workspace = topWorkspace
# Get dict of months and month-number (i.e. January = 001, March = 003 etc.)
months = {calendar.month_name[i].upper(): str(i).zfill(3) for i in range(1, 13)} # Get dict of months and month number (i.e. January = 001, March = 003 etc.)
# Step through list of all folders
for folderPath in arcpy.ListWorkspaces():
 baseName = os.path.basename(folderPath).upper()
 if baseName in months: # Test that subfolder is a month name
 monthNumber = months[baseName] # Get month-number for use in output filename
 arcpy.env.workspace = folderPath
 rasterList1 = arcpy.ListRasters('*Max_Temper.tif')
 rasterList2 = arcpy.ListRasters('*Min_Temper.tif')
#Calculate maen
 ws_out = (rasterList1 + rasterList2) / 2
outRasterName = os, path.join(ws_out, "Mean_Temp_{}.tif".format(monthNumber))
#print done
print 'done'
0 Kudos
XanderBakker
Esri Esteemed Contributor

You are trying to "divide" the two lists by two (line 19). The lists are no raster objects. You should use the combined list as input for the CellStatistics tool.

the ws_out should be the name of the folder (workspace) where you want to store the resulting rasters.

Furthermore, on line 20 you have "os,  path" it should be "os.path"

0 Kudos
XanderBakker
Esri Esteemed Contributor

... or to be more specific, something like this:

import arcpy, os, calendar
from arcpy.sa import *
arcpy.CheckOutExtension("Spatial")
arcpy.env.parallelProcessingFactor = "100%"
topWorkspace = r'D:\SWAT-WEATHER-DATA2'
ws_out = r'D:\SWAT-WEATHER-DATA2\MeanRasters' ### create this folder!!!
arcpy.env.workspace = topWorkspace

# Get dict of months and month-number (i.e. January = 001, March = 003 etc.)
months = {calendar.month_name[i].upper(): str(i).zfill(3) for i in range(1, 13)} # Get dict of months and month number (i.e. January = 001, March = 003 etc.)


# Step through list of all folders
for folderPath in arcpy.ListWorkspaces():
    baseName = os.path.basename(folderPath).upper()
    if baseName in months: # Test that subfolder is a month name
        monthNumber = months[baseName] # Get month-number for use in output filename
        arcpy.env.workspace = folderPath

        # list rasters
        rasterList1 = arcpy.ListRasters('*Max_Temper.tif')
        rasterList2 = arcpy.ListRasters('*Min_Temper.tif')

        # combine lists
        rasterList = rasterList1 + rasterList2

        # Execute CellStatistics
        outCellStatistics = CellStatistics(rasterList, "MEAN", "NODATA")

        #Save the output
        outRasterName = os.path.join(ws_out, "Mean_Temp_{}.tif".format(monthNumber))
        outCellStatistics.save(outRasterName)

#print done
print 'done'
XanderBakker
Esri Esteemed Contributor

... and maybe you should include a statement to check the length of the rasterList before you execute the CellStatistics tool. If you come across an empty folder you don't want to try to continue with the CellStatistics.

ShouvikJha
Occasional Contributor III

Xander Bakker‌ . yes i have executed this function before performing cell-statistics to get the list of raster as per your suggestion . Thank you 

print rasterList‍
0 Kudos
XanderBakker
Esri Esteemed Contributor

Actually I was referring at doing something like this (see line 4):

        # combine lists
        rasterList = rasterList1 + rasterList2

        if len(rasterList) > 1:
            # Execute CellStatistics
            outCellStatistics = CellStatistics(rasterList, "MEAN", "NODATA")

            #Save the output
            outRasterName = os.path.join(ws_out, "Mean_Temp_{}.tif".format(monthNumber))
            outCellStatistics.save(outRasterName)

I use "> 1", not sure what happens if the list would contain a single raster...

Anyway, I'm glad it works!