0

I have created several rasters using arcpy by subtracting several rasters using the arcpy.Minus_3d function Now I want to clip these rasters using polygons. My rasters are called "test01_out", "test02_out" etc. My polygons are called "test poly_name_test01.shp", "test poly_name_test02.shp", etc.

Is there a way to clip raster "test01_out" with polygon "test poly_name_test01.shp" using arcpy? (I used QGis to split my shapefile into separate shapefiles based on attributes) Alternatively, how can I call the polygon in a shapefile containing all my shapefiles based on attribute (name=test01)?

I've been trying with this code but I'm stuck

import arcpy
import os
from arcpy import env

env.workspace = r"C:\rasters"

list1 = arcpy.ListRasters("test*out")
list2 = arcpy.ListFeatureClasses("*.shp")
for raster in list1:
    rasterName = os.path.basename(raster) #I know this is wrong - I somehow need to remove the _out
    rasterMask = ""
    for mask in list2:
            if mask.endswith(rasterName):
                rasterMask = mask
                print "mask: " + mask
                break
        if rasterMask !="":
            clipFile = rasterName + "_clip"
            print "clip file: " + clipFile
            arcpy.Clip_analysis(raster, env.workspace + "\\" + mask, env.workspace + "\\" + clipFile)
  • Clip analysis is vector based clipping. Try the extract by mask. – Keagan Allan Mar 21 '18 at 5:49
  • mask only removes empty cells? – Nuttieke Mar 21 '18 at 6:05
  • 2
    Based on the first part of your question you asked if you could clip the raster. The "clip_analysis" tool is for vector based clipping. Try using the spatial analyst "extract by mask" to do the raster based clipping. – Keagan Allan Mar 21 '18 at 6:19
  • Thank you, I was looking at mask in stead of extract by mask – Nuttieke Mar 22 '18 at 5:09
3

As @KeaganAllan said, Clip_analysis clips features(vectors) by features, not rasters. Use arcpy.sa.ExtractByMask().

out_raster = arcpy.sa.ExtractByMask(raster, env.workspace + "\\" + mask)
out_raster.save(env.workspace + "\\" + clipFile)

Detailed information is on Extract by Mask - Help | ArcGIS

  • Yay, thank you! That works! Another small question, in arcgis this file is added to my map and is called out_raster, but in my folders it's called test01_clip, is there a way to have the same name on the map? – Nuttieke Mar 22 '18 at 5:06
  • I would pose this as a new question. You have the answer to the original question, adding more questions in the comments "muddies" the Questions and Answers provided. You can always link the new question to this one by referring to it. – Keagan Allan Mar 22 '18 at 7:44

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.