How to Get Sum of Table Column Values into Python Variable in ArcGIS

arcgis-10.1arcgis-desktoparcpy

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?

Best Answer

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)