1

I have a list of rasters, created by arcpy using ListRasters. Rasters are stored in a geodatabase. How can I subset only one raster of the raster list? The goal is to make a new list, but containing only one raster file.

Ultimate goal is to loop through list of rasters and calculate Area solar radiation for each one of them. But, but for learning/training purposes I wish to explore my parameters only on single raster for now. (I know I can read-in just single raster, but I thought that subsetting might be easy as well?)

I have thought that I can simply subset the element by the index value, but this seems not working in arcpy. Any advices? I think I am missing something very obvious...

import arcpy, os

# Set working environment
arcpy.env.workspace = os.path.join(inWD, "output/bufRastTwins.gdb")

# List all rasters with defined name wildcard: r_1, r_2, r_3.. to r_100
allRasters = arcpy.ListRasters("r_*")

# Select the first raster from the rasters list
myRasters = allRasters[0]
print myRasters

My attempt leads to loop through raster name, not throught the subsetted raster itself:

print myRaster:
r_1  # first element succesfully created

but for raster in myRasters:
   print raster    # this is obviously wrong

r
_ 
1
  • Hi @BERA, thank you for your comment. I am trying to calculate solar radiation afterwards, but for making a script I wanted to run it simply on one raster. I have completed my question to answer your comment. – maycca Aug 26 '19 at 9:14
  • arcpy.ListRasters is only returning a list containing "raster names in the workspace". Extracting the first element of this list is only giving you the first raster name within the specified workspace. With it you can do something like os.path.join(inWD, "output/bufRastTwins.gdb", allRasters[0] to hae the full path plus name of your raster and use this as your input for further analysis. – umbe1987 Aug 26 '19 at 9:21
2

This myRasters = allRasters[0] will select first element of the list which is a string. So if you loop over it you loop over each characher in it which is what you see:

rasters = ['abc','def']

for raster in rasters[0]:
    print(raster)
a
b
c

You can slice the list like this which will return a list of only the first element:

for raster in myRasters[:1]:
   print(raster)
abc

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.