ArcGIS Pro 3.1.7 - Calculate Fields geoprocessing not using expression!

455
3
11-22-2023 06:50 AM
VincentLaunstorfer
Occasional Contributor III

Hi,

I have a simple script using CalculateFields geoprocessing tool. As part of my script, I build an expression in a loop for fields to calculate. However, it is not working...

If I use hard-coded field names and expression for calculation, it works.

Why my 'expression' string variable is not working? It is exactly the same as the hard-coded string...

arcpy.management.CalculateFields(in_table=fc, expression_type="PYTHON3", fields=[["Detached", "!Detached!*!Ratio!", ""], ["Total", "!Total!*!Ratio!", ""]])[0]

arcpy.management.CalculateFields(in_table=fc, expression_type="PYTHON3", fields=expression)[0]

 

0 Kudos
3 Replies
VincentLaunstorfer
Occasional Contributor III

I found a workaround... Instead of dealing with building an 'expression' string variable in a for loop to calculate all fields with CalculateFields, I am calculating fields directly in the for loop, one by one with  arcpy.management.CalculateField. It is just as good and the syntax is much easier!

GIS-Chops
New Contributor III

It would be helpful if you posted the contents of the expression variable and any errors that come up when attempting to run the tool.

The tool is expecting a Value Table which is essentially an array of arrays. If you enclosed your value table in quotes it isn't getting the proper input. I am also wondering what the [0] at the end of each line is for?

I'm thinking this would work:

arcpy.management.CalculateFields(in_table=fc, expression_type="PYTHON3", fields=[["Detached", "!Detached!*!Ratio!", ""], ["Total", "!Total!*!Ratio!", ""]])[0]
expression = [["Detached", "!Detached!*!Ratio!", ""], ["Total", "!Total!*!Ratio!", ""]]
arcpy.management.CalculateFields(in_table=fc, expression_type="PYTHON3", fields=expression)[0]

 

0 Kudos
VincentLaunstorfer
Occasional Contributor III

Thanks for looking at this post.

The content of the expression variable is the second line of the code, as below:

[["Detached", "!Detached!*!Ratio!", ""], ["Total", "!Total!*!Ratio!", ""]]

 As you mentioned, the CalculateFields is expecting a Value table and here I tried to built a string. In fact, I tried to reuse the syntax provided when you export ModelBuilder to python... hence the [0] which I do not either understand its use.

As for error message, on runtime, Python simply ignore the CalculateFields!

As I said, using arcpy.management.CalculateField in a loop is an excellent workaround, using simple string variable (no need for Value table)

0 Kudos