2

I want to simply add two rasters within a python script using map algebra, which from what I understand is the equivalent to adding two rasters in the raster calculator.

If I do this using raster calculator and simply type "Raster1 + Raster2", it works perfectly. However, if I run this in a python script, I get error000732: Input Raster: Dataset Raster1 does not exist or is not supported.

Here is my code:

import arcpy
from arcpy import env
from arcpy.sa import *
raster1 = ("C:/raster1")
raster2 = ("C:/raster2")
raster3 = Raster("raster1") + Raster("raster2")

I set up the syntax based on the Esri help page for Map Algebra http://desktop.arcgis.com/en/arcmap/latest/extensions/spatial-analyst/map-algebra/an-overview-of-the-rules-for-map-algebra.htm

I'm not sure why my rasters are recognized within the raster calculator but not map algebra.

  • 6
    I think your last line should probably read raster3 = Raster(raster1) + Raster(raster2) without the double quotes although I can't confirm if this will solve the issue (not an ArcMap user) :) – Joseph Jun 22 '17 at 14:56
  • I have confirmed Joseph's answer here (with ArcMap version 10.0) – cm1 Jun 22 '17 at 16:19
  • ah yes, removing the double quotes does the trick! Thank you! – Marina Jun 22 '17 at 17:34
3

What @Joseph says. The Raster class needs a string containing the path to your raster. You've correctly assigned this to a variable, so you then need to pass those variables to instantiate your Rasters. This code should work:

import arcpy
from arcpy import env
from arcpy.sa import *
raster1 = ("C:/raster1")
raster2 = ("C:/raster2")

#Note lack of quotes in following line
raster3 = Raster(raster1) + Raster(raster2)

#Don't forget to save eg:
raster3.save("C:/raster3")

The reason the documentation you link shows the rasters being passed to map algebra statements in quotes is because they assume you are typing in the python console in ArcMap. If you're raster datasets are open in ArcMap you can refer to them by their name in the table of contents, using quotes.

In which case the necessary code would be

import arcpy
from arcpy import env
from arcpy.sa import *

#No need to assign paths to variables.
#NB You still need to call `Raster()` in order to tell Arcpy that the '+' is for raster math. 
raster3 = Raster("raster1") + Raster("raster2")

#Don't forget to save eg:
raster3.save("C:/raster3")
0

Just adding another suggestion in case someone else has this problem as well. I had to include the raster file format (TIF, IMG..) in order to to get the save function to work for me in my Python script.

Here is an example:

raster3.save("C:/raster3.tif")

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.