2

what I want to do is add multiple raster layers stored in FGDB together using the raster calculator in arcpy

To start off I have seen this question Using Loop with Raster Calculator in ArcPy?

this is what it would look like in arcgis raster calculator

'remap1'+'remap2'+'remap3'+'remap4'+'remap5'+'remap6'+'remap7'+'remap8'+'remap9'+'remap10'+'remap11'+'remap12'+'remap13'+'remap14'+'remap15'+'remap16'+'remap17'+'remap18'+'remap19'+'remap20'+'remap21'+'remap22'+'remap23'+'remap24'+'remap25'+'remap26'+'remap27'+'remap28'+'remap29'+'remap30'+'remap31'

now in Python

import arcpy
from arcpy.sa import *
arcpy.env.workspace=env
reclass1 = '+'.join(["Raster("+"r'{}'".format(x)+")" for x in arcpy.ListRasters() if x[:5]=='remap' if int(x[5:]) < 14 ])
print reclass1

which prints out to

 Raster(r'remap1')+Raster(r'remap2')+Raster(r'remap3')+Raster(r'remap4')+Raster(r'remap5')+Raster(r'remap6')+Raster(r'remap7')+Raster(r'remap8')+Raster(r'remap9')+Raster(r'remap10')+Raster(r'remap11')+Raster(r'remap12')+Raster(r'remap13')

now how do I execute this command and save it to new Raster file?

b=Raster(reclass1)
b.save("blah")

Traceback (most recent call last):
  File "R:\Data\LUCZ_2017\ConservationPriorityAreas\cons.py", line 36, in <module>
    Raster_Calculator(env2)
  File "R:\Data\LUCZ_2017\ConservationPriorityAreas\cons.py", line 34, in Raster_Calculator
    b=Raster(reclass1)
RuntimeError: ERROR 000732: Input Raster: Dataset Raster(r'remap1')+Raster(r'remap2')+Raster(r'remap3')+Raster(r'remap4')+Raster(r'remap5')+Raster(r'remap6')+Raster(r'remap7')+Raster(r'remap8')+Raster(r'remap9')+Raster(r'remap10')+Raster(r'remap11')+Raster(r'remap12')+Raster(r'remap13') does not exist or is not supported

update

reclass1 = [Raster(x) for x in arcpy.ListRasters() if x[:5]=='remap' if int(x[5:]) < 14 ]
print reclass1

print sum(reclass1)

use the regular python sum tool??

Traceback (most recent call last):
  File "C:\Users\Desktop\abid.py", line 19, in <module>
    print sum(reclass1)
RuntimeError: ERROR 999998: Unexpected Error.
3
  • 1
    reclass1 is a string: 'Raster(r'remap1')+Raster(r'remap2')...' That is probably why it is not working
    – BERA
    Jun 7, 2018 at 16:12
  • okay that is helpful but doesn't completely answer my question
    – ziggy
    Jun 7, 2018 at 16:21
  • I doubt it is possible to build an expression like that. You would need to "unpack" it. Use cell statistics with sum instead.
    – BERA
    Jun 7, 2018 at 16:26

1 Answer 1

1

I would use the Cell Statistics tool, just look at the code sample at the bottom of the page. You've cracked the code to create a list of raster names just feed that into the tool.

2
  • okay I will give this a try
    – ziggy
    Jun 7, 2018 at 16:29
  • nice, thanks. Rasters in python is a bit tricky tbh
    – ziggy
    Jun 7, 2018 at 18:01

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