Field Calculator Expression Inside a Python Script

817
2
Jump to solution
10-28-2013 11:10 AM
DamonOsbourne
New Contributor II
Ok, imagine there are 3 fields in a table: Field1, Field2, and and empty Field3. All I want to do is multiply Field1 * Field2 and populate the result in Field3. This is easily done in the field calculator in ArcMap, but what does the code look like in a python script? I am assuming that the arcpy tool I need is Calculate Field, but am not 100% certain. The part I am stuck on is what does the 'expression' look like in the code line below... or if a different tool is better, what is it?

CalculateField_management (in_table, field, expression, {expression_type}, {code_block})
Tags (2)
0 Kudos
1 Solution

Accepted Solutions
JakeSkinner
Esri Esteemed Contributor
Hi Damon,

It would look something like the below:

arcpy.CalculateField_management(featureclass, "field3", "!field1! * !field2!", "PYTHON_9.3","#")


One good trick that you can do is execute the tool in ArcMap, then go to your Results window.  Here you can right-click on the results > Copy As Python Snippet.

[ATTACH=CONFIG]28664[/ATTACH]

View solution in original post

0 Kudos
2 Replies
JakeSkinner
Esri Esteemed Contributor
Hi Damon,

It would look something like the below:

arcpy.CalculateField_management(featureclass, "field3", "!field1! * !field2!", "PYTHON_9.3","#")


One good trick that you can do is execute the tool in ArcMap, then go to your Results window.  Here you can right-click on the results > Copy As Python Snippet.

[ATTACH=CONFIG]28664[/ATTACH]
0 Kudos
curtvprice
MVP Esteemed Contributor
String formatting in Python makes this kind of thing much easier to write and debug. For example:

expr = "!{0}! * !{1}!".format("FIELD1", "FIELD2")
arcpy.CalculateField_management(featureclass, "FIELD3", expr, "PYTHON_9.3")


There are many on the forums that urge us to always use a cursor for these calculations (for performance reasons) but I still use Calculate Field for simple expressions like this because it is less hassle for me.
0 Kudos