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. 
asked Oct 1, 2017 at 11:31
1
  • Read the documentation on creating a Python function. What you have right now tries to execute immediately Commented Oct 1, 2017 at 12:36

1 Answer 1

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")
answered Oct 1, 2017 at 17:09
0

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.