[GIS] Why can’t I multiply two string fields in the Field Calculator by converting them to int() and float()

arcgis-10.0arcpyfield-calculator

I'm using ArcGIS 10 and new at python scripting. I have a string field that I need to calculate by multiplying two other string fields. I can do it in python using two arbitrary values…

CINPT1 = "1.00"
CNETVAL = "8500"

print int(float(CINPT1) * int(CNETVAL))

but…I need this as an arcpy fieldcalculation. What I have now is below. I'm basically trying to what is above: the CNETVAL field should equal CINPT1 * CUNITV

import arcpy, sys, string, os

MAPCHAR = "MAPCHAR"
CINPT1 = "CINPT1"
CNETVAL = "CNETVAL"
CUNITV = "CUNITV"

expression = "multiStringFunc(!CNETVAL!)"
codeblock = """def multiStringFunc(netvalue):
    value1 = float(CINPT1)
    unitvalue = int(CUNITV)
    netvalue = int(value1 * unitvalue)

    return netvalue"""

# Process: CUNITV = CINPT1 * CUNITV
arcpy.CalculateField_management(MAPCHAR, CINPT1, expression, "Python", codeblock)

What i get in return is "global name 'CINPT1' is not defined". I am pretty new at using python, so i don't know if I'm just using the value wrong within the codeblock or I'm just totally off. Anything you can contribute would be appreciated. Thanks!

Best Answer

Your inputs are being defined as strings, not field names, therefore instead of passing the value of field "CINPT1" to your code, you are passing the string "CINPT1". You need to use an Update Cursor to get field values and pass THAT into your calculation instead of a string.

Your code should go something like this:

import arcpy

inputFeature = r'C:\YourFeatureLocation'

rows = arcpy.UpdateCursor(inputFeature)
for row in rows:
    row.CNETVAL = row.CINPT1 * row.CUNITV
    rows.updateRow(row)

del row, rows

My apologies if this isn't quite right, I'm don't have access to arcpy for testing right now. This is the concept you should be pursuing.

On a side note, the error you are getting appears to be an issue of scope. You are defining a python function "codeblock" outside of your current python code if that makes sense.... this code block doesn't have access to variables that are defined outside of it.