I'm writing a python script that loops through a number of input data sets and in the process adds a new field with a unique field name and populates it with a value at the same time the script records the field names in a list for later use. These data sets are then unioned together at the of the script and I'd like to build in the function to sum all the newly added fields into a total field at the end. I'm trying to use the calculate field tool to sum the fields, but I cannot seem to get it right and I can't seem to figure it out.
Solved! Go to Solution.
Show your script. But basically you just need to provide the field list and if all the values are numeric it is a simple list sum in an update cursor in your new field.
Alternately, you can extract the numeric fields to a numpy array, do the summation there, then use arcpy.da.ExtendTable to permanently join the result back to your input table.
I never got past trying to pass the list into the calculate field, all the fields in the list are numeric.
arcpy.CalculateField_management(input_layer, "total", sum(URC_field_list), "PYTHON3")
Can you paste the Python Snippet and results? Since we can't see how URC_field_list is defined, it is hard to know what maybe be going on. Also, you haven't said whether you are getting errors or unexpected results. Either way, it helps to provide more details.
You might want to have a look at this post: Get Statistics From All Fields in an Attribute Table , but probably as others have already requested, providing the code that you have, will provide the insights to make some suggestions of how you can solve this.
Joe Borgione , with all the discussions already on GeoNet it is likely that this is not the first time this subject has been touched. The one I referred at in my post was a different case where the summary statistics of a field were needed. What I came up with does create statistics of multiple value for a single feature, so I thought it could contain some relevant code that could be tweaked for this case.
The Field Calculator is the wrong tool for this task and cannot be used to solve the problem. As others have mentioned a SearchCursor should be used to read all of the records except the summary record to sum the values and then an UpdateCursor can write the result to the summary record if it exists or an InsertCursor can create a summary record if it doesn't exist.