1

I need to calculate the difference between two input parameters within a table. the first parameter is a field in the table, and the second is a constant i want to subtract from this field, both of which are asked for in a script/tool.

currently my code looks like this:

heightfield = arcpy.GetParameterAsText(4) # field (float) in table inObsPtswHeight
heightOffset = arcpy.GetParameterAsText(5) # linear unit, constant value
arcpy.CalculateField_management(inObsPtswHeight, heightfield, heightfield - heightOffset, "PYTHON")

This is run in an arcgis script toolwindow and returns the error:

arcpy.CalculateField_management(inObsPtswHeight, heightfield, heightfield - heightOffset, "PYTHON")
TypeError: unsupported operand type(s) for -: 'unicode' and 'unicode'

EDIT: Bera have given around 70 % of the answer: the first argument (which is a field) cannot be changed to float because it is a field name. the second argument however can.

heightfield = arcpy.GetParameterAsText(0)
#line above: field in table inObsPtswHeight - this is left unchanged
heightOffset = float((re.findall("\d+\.\d+",arcpy.GetParameterAsText(1)))[0]) 
# linear unit, constant value - a linear unit returns a string (e.g. "102.9 meters") 
# which has to be stripped into only the number/float. this line returns a float.


arcpy.CalculateField_management(inObsPtswHeight, heightfield, "!{0}! - {1}".format(heightfield, heightOffset), "PYTHON")
# as Bera pointed out, the smartest is putting the expression into a string. 
#to call on the field in a python field calculator expression, you have to use !fieldname!, while the float can be used directly. 
  • Read the documentation on creating a Python function. What you have right now tries to execute immediately – Vince Oct 1 '17 at 12:36
0

arcpy.GetParameterAsText return strings so you are trying to subtract two strings which will not work. Try converting them to float:

heightfield = float(arcpy.GetParameterAsText(4)) # field (float) in table inObsPtswHeight
heightOffset = float(arcpy.GetParameterAsText(5)) # linear unit, constant value

Also i think you are supposed to enclose the expression in quotes:

arcpy.CalculateField_management(inObsPtswHeight, heightfield,'{0} - {1}'.format(heightfield,heightOffset), "PYTHON")

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.