8

Im creating a script to calculate some new fields in Arcgis10.1 using the arcpy library. I need to sum the total of a table column in order to calculate a new field. I wanted to ask if it is possible to store all the values in an array so i can get the total sum and use the variable in the new field calculation?

2 Answers 2

13
summed_total = 0
with arcpy.da.SearchCursor(fc, "field to be totaled") as cursor:
    for row in cursor:
        summed_total = summed_total + row[0]

Something like this would work. Replace what's in quotes with your field name, or with a list of fields you're going to be working with. Replace fc with the feature that holds the field.

That won't work for 10.0 or earlier; da.SearchCursor didn't show up until 10.1. For earlier versions:

summed_total = 0
field = "field to be summed"
with arcpy.SearchCursor(fc):
    for row in cursor:
        summed_total = summed_total + row.GetValue(field)
4
  • 3
    the data access module (resources.arcgis.com/en/help/main/10.1/index.html#//…) was introduced at 10.1
    – Nxaunxau
    Jan 8, 2014 at 2:26
  • 1
    Yep, you're right. Ignore that second example, the da.SearchCursor is a much better option. Jan 8, 2014 at 2:26
  • This worked pretty good i made some small changes to fit my script but overall it was exactly what needed
    – Daniel
    Jan 8, 2014 at 17:22
  • 2
    Here's the one-liner: summed_total = sum((r[0] for r in arcpy.da.SearchCursor(fc, ['FIELDNAME'])))
    – nmpeterson
    Oct 7, 2014 at 14:12
5

You can accomplish this in two lines when working with numpy arrays (TableToNumPyArray).

import arcpy, numpy

fc = r'C:\path\to\your\fc'

# Convert to numpy array.  "test" is the field name
field = arcpy.da.TableToNumPyArray (fc, "test", skip_nulls=True)
sum = field["test"].sum() 

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.