ArcPy – How to SUM Field and Insert into NULL Column Using ArcGIS 10.2

arcgis-10.2arcpyfield-calculator

I am only in the beginning stages of learning Python.

I have a column, 'QUANTITY_SOLID', that I want to take the sum of all of its rows. I understand I can do this with 'SUMMARY_STATISTICS', but i'm not trying to create another entire table nor do anything other than simply SUM up that column. Once I have it summed up, I want to insert the sum into a new NULL field that I have created – I am attempting to do this via the 'CALCULATE_FIELD' tool.

QUANTITY_SOLID

QUANTITY_SOLID_SUM

CALCULATE_FIELD

Best Answer

Cursors are the way to go for this type of problem.

First, create a list of values using a Search Cursor and a generator expression:

b = sum(row[0] for row in arcpy.da.SearchCursor(fc, 'QUANTITY_SOLID'))

Then run an Update Cursor to populate the QUANTITY_SOLID_SUM field:

with arcpy.da.UpdateCursor(fc, ['QUANTITY_SOLID_SUM']) as cursor:
    for row in cursor:

Finally, update the rows with the value from the generator

    row[0] = b
    cursor.updateRow(row)

import arcpy

# Define the feature class
fc = r'C:\path\to\your\fc'

# Use a generator expression to populate a list from the 'QUANTITY_SOLID' field
b = sum(row[0] for row in arcpy.da.SearchCursor(fc, 'QUANTITY_SOLID'))

with arcpy.da.UpdateCursor(fc, ['QUANTITY_SOLID_SUM']) as cursor:
    for row in cursor:
        row[0] = b
        cursor.updateRow(row)