How to set reclassification codes as parameters in python script

4713
6
05-09-2012 02:48 PM
by Anonymous User
Not applicable
Original User: davisam1

Hi All,
I am working on a python script and I would like the user to be able to change the values that get reclassed.  If I hard code the remap fields into the code then the program does what it is supposed to do but if I put the part of the code ([11,94,0],[95,95,1]) as a string in the parameters then the code runs but doesn't reclass anything.  I've pasted that part of my code below as well as two screengrabs of how I set up the model parameters. 
Does anyone have an example on how to set this up in python (i'm using ArcGIS10) and how to set up the model parameters correctly? 
Thank you for your help in advance.
Amelie


# Set the necessary product code
# import arcinfo


# Import arcpy module
import arcpy
from arcpy import env

# Check out any necessary licenses
arcpy.CheckOutExtension("spatial")

###################### Script arguments

Input_Land_Cover__NLCD_2006_ = arcpy.GetParameterAsText(0)
#Input_Land_Cover__NLCD_2006_ = "D:\\DATA\\NLCD\\nlcd2006_cook" # provide a default value if unspecified

Output_Workspace = arcpy.GetParameterAsText(1)
#Output_Workspace = "D:\\DATA\\DELETE" # provide a default value if unspecified

# Set environment settings
env.workspace = Output_Workspace

Zone_values_you_want_to_shrink__LC_code_ = arcpy.GetParameterAsText(2)
#Zone_values_you_want_to_shrink__LC_code_ = "11" # provide a default value if unspecified

Land_Cover_Code_for_which_you_want_to_extract_distance_measure = arcpy.GetParameterAsText(3)
#Land_Cover_Code_for_which_you_want_to_extract_distance_measure = "[11,94,0],[95,95,1]" # provide a default value if unspecified


####################
# could try this: tmp3 = Reclassify(Int(EucDistance(inR, "", "1000", "")), "VALUE", "0 NODATA", "DATA")

# Process: Reclassify
remap = arcpy.sa.RemapRange([Land_Cover_Code_for_which_you_want_to_extract_distance_measure])
nlcd_ag = arcpy.sa.Reclassify(Input_Land_Cover__NLCD_2006_, "VALUE", remap, "DATA")
out_rc1 = Output_Workspace + "\\out1"
nlcd_ag.save(out_rc1)






[ATTACH=CONFIG]14222[/ATTACH]
[ATTACH=CONFIG]14223[/ATTACH]
0 Kudos
6 Replies
curtvprice
MVP Esteemed Contributor

Does anyone have an example on how to set this up in python (i'm using ArcGIS10) and how to set up the model parameters correctly? 


You could get pretty fancy with parameter validation and such, but to do it the way you're trying to would be pretty straightforward:

listString = arcpy.GetParameterAsText(3) # "[11,94,0],[95,95,1]" 
# compose a line of python code and run it with exec()
exec("remap = arcpy.sa.RemapRange(%s)" % listString)
# the variable remap now has your remap range for the Reclassify tool


An easy way to get the python syntax right for complex functions like this is to run the tool interactively and then open the geoprocessing results, right click the record of your tool run, and "Copy As Python Snippet".

Update: I edited this post to change my advice, but not before Amelie implemented my original suggestion (below), which was to build the lists from input text parameters with the .split() function. The reason I changed my suggesion to what is above is because the reclass input can be very complex and entering string representation of a python list and interpreting it with exec() allows for more flexibility in syntax.
0 Kudos
by Anonymous User
Not applicable
Original User: davisam1

Worked like a charm.
Thank you greatly,
Amelie

Your code integrated in what I originally posted:


# Set the necessary product code
# import arcinfo


# Import arcpy module
import arcpy
from arcpy import env

# Check out any necessary licenses
arcpy.CheckOutExtension("spatial")

###################### Script arguments

Input_Land_Cover__NLCD_2006_ = arcpy.GetParameterAsText(0)
#Input_Land_Cover__NLCD_2006_ = "D:\\DATA\\NLCD\\nlcd2006_cook" # provide a default value if unspecified

Output_Workspace = arcpy.GetParameterAsText(1)
#Output_Workspace = "D:\\DATA\\DELETE" # provide a default value if unspecified

# Set environment settings
env.workspace = Output_Workspace

Zone_values_you_want_to_shrink__LC_code_ = arcpy.GetParameterAsText(2)
#Zone_values_you_want_to_shrink__LC_code_ = "11" # provide a default value if unspecified

# In the tool interface you can set defaults
fromClass =  arcpy.GetParameterAsText(3)   # "11 94 0"
toClass = arcpy.GetParameterAsText(4)      # "95 95 1"

# convert strings to lists of reclass values
# using try/except to handle any syntax problems that come up
try:
    fromClassList = fromClass.split()
    toClassList = toClass.split()
    # convert values to integer
    fromClassList = [int(k) for k in fromClassList]
    toClassList = [int(k) for k in toClassList]
    if len(fromClassList) <> len(toClassList): raise Exception
except:
    raise Exception, "Invalid input for From and To Classes"


####################

# Process: Reclassify
remap = arcpy.sa.RemapRange([fromClassList,toClassList])
nlcd_ag = arcpy.sa.Reclassify(Input_Land_Cover__NLCD_2006_, "VALUE", remap, "DATA")
out_rc1 = Output_Workspace + "\\out1_f"
nlcd_ag.save(out_rc1)


0 Kudos
curtvprice
MVP Esteemed Contributor
Reclassify is a tricky thing - just wanted to add to the thread that to allow more than two ranges, you could put your range remaps into a single string variable like this:

"start end newvalue, start end newvalue, start end newvalue"

These could be converted into a Python list for the RemapRange() function:

rangeText = "0 1 99, 1 2 100"
temp = rangeText.split(",") # split to two strings at the comma
temp = [k.split() for k in temp] # split each remap group into strings
temp = [ [int(j) for j in k] for k in temp]  # integerize values  


I tested this in a Python window:
>>> rangeText = "0 1 99, 1 2 100"
>>> temp = rangeText.split(",") 
>>> temp
['0 1 99', ' 1 2 100']
>>> temp = [k.split() for k in temp]
>>> temp
[['0', '1', '99'], ['1', '2', '100']]
>>> temp = [ [int(j) for j in k] for k in temp]
>>> temp
[[0, 1, 99], [1, 2, 100]]
0 Kudos
by Anonymous User
Not applicable
Original User: davisam1

even better.   Thank you!
0 Kudos
PriyankaSharma1
New Contributor
Hi,

I am trying to perform reclassification on a shape file having several attributes[ATTACH=CONFIG]15757[/ATTACH]. I am trying to call this attribute table and "LANDCOVER" column into my python script to perform reclassification.

I am using this python script to perform this:

fc = "D:\Priyanka\Model_tests\Reclassify_LU_Del\LANDUSE4_prj.shp"
fldName = 'LANDCOVER'
def reclass(landcover):
  if landcover in ("Drain", "Lake", "River", "Water Body", "Canal"):
    return "Water"
  elif landcover in ("Green Area", "Open Space"):
    return "Green and Open Space"
  elif landcover in ("Island"):
    return "Miscellaneous"
  elif landcover in ("Others"):
    return "Public Space"
  else:
    return landcover

But, I am getting errors "Invalid Syntax". I am sure that I am doing something wrong but dont know what! It would be great if you can please let me know how to perform reclassification on this attribute table and then incorporate the same to ARC Tool!

Thanks!
0 Kudos
by Anonymous User
Not applicable
Original User: curtvprice

Hi,

I am trying to perform reclassification on a shape file having several attributes[ATTACH=CONFIG]15757[/ATTACH]. I am trying to call this attribute table and "LANDCOVER" column into my python script to perform reclassification.

I am using this python script to perform this:

fc = "D:\Priyanka\Model_tests\Reclassify_LU_Del\LANDUSE4_prj.shp"
fldName = 'LANDCOVER'
def reclass(landcover):
  if landcover in ("Drain", "Lake", "River", "Water Body", "Canal"):
    return "Water"
  elif landcover in ("Green Area", "Open Space"):
    return "Green and Open Space"
  elif landcover in ("Island"):
    return "Miscellaneous"
  elif landcover in ("Others"):
    return "Public Space"
  else:
    return landcover


But, I am getting errors "Invalid Syntax". I am sure that I am doing something wrong but dont know what! It would be great if you can please let me know how to perform reclassification on this attribute table and then incorporate the same to ARC Tool!

Thanks!


To modify field values in a table, you need to use the Calculate Field tool. Fortunately, your nifty function can easily be used there as a code block:

fc = "D:\Priyanka\Model_tests\Reclassify_LU_Del\LANDUSE4_prj.shp"
fldName = 'LANDCOVER'
newFldName = 'LANDCOV1'
arcpy.AddField_management(fc,newFldName,"TEXT") 
arcpy.CalculateField_management(fc,newFldName,"reclass(!%s!)" % fldName, "PYTHON",
"""
def reclass(landcover):
  if landcover in ("Drain", "Lake", "River", "Water Body", "Canal"):
    return "Water"
  elif landcover in ("Green Area", "Open Space"):
    return "Green and Open Space"
  elif landcover in ("Island"):
    return "Miscellaneous"
  elif landcover in ("Others"):
    return "Public Space"
  else:
    return landcover
"""


You can modify this into a script tool by following these instructions in the help:

A quick tour of creating script tools
0 Kudos