[GIS] Field calculator or update cursor

arcgis-10.0cursorfield-calculatorpython

I have a feature class in which one field (let's call it "Field_A"), as yet empty, is to be populated by the contents of another field ("Field_B") multiplied by a certain number (I'll call it the "constant"). Would it be a good idea to simply populate Field_A using an update cursor, as follows:

rows = arcpy.UpdateCursor(InTable) 
for row in rows:
     row.Field_A = row.Field_B * constant
     rows.updateRow(row) 
del row, rows

, or do I have to use the field calculator? If I have to use the field calculator, I'm having an issue with the syntax. I defined the expression thus:

expression = "Field_A * constant"

and the code is as follows:

arcpy.CalculateField_management(InTable, "Field_A", expression)

When using CalculateField as shown, the script runs without errors, but "Field_A" is populated with zeros as a result. What am I doing wrong with CalculateField, or should I simply use an update cursor?

Best Answer

I think you could go either way with this code. Your first code block would run correctly.
I imagine there are some speed differences between looping through rows and doing a calculate values, so the latter is probably much faster.

Try this for the field calculator expression:

expression = "!Field_B! * constant"

arcpy.CalculateField_management(InTable, "Field_A", expression, "PYTHON_9.3")

You did not have the required field delimiter for the field name in the expression string. Fields have to be wrapped with a "!", just like they would appear in the Field Calculator window in ArcMap when using a python expression. Also note that I added PYTHON_9.3 to the end, which will invoke the more current version of the geoprocessor. Read the Calculate Field (Data Management) help entry, for more information.

Here is a screenshot of the Field Calculator window for reference: Field Calculator Window

Related Question