3

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

3
  • 3
    Are you looking for a Python scripting solution or do you need to do this entirely in the field calculator?
    – Aaron
    Commented Aug 7, 2014 at 21:21
  • @ Aaron, Honestly either would be fine. I'm trying to learn as much Python as I can but learning how to do it either way would be great. Commented Aug 7, 2014 at 21:32
  • 1
    I think JumpinInTheFire is appropriate! You need to use a cursor, in this case an arcpy.da.searchcursor and arcpy.da.updatecursor. Google that and if you have difficulty understanding them I'll provide some code. Commented Aug 7, 2014 at 21:34

1 Answer 1

8

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)
4
  • 1
    I like that Aaron for the simplicity! Please note JumpinInTheFire that that is not a field calculator expression. Commented Aug 7, 2014 at 21:41
  • 1
    Awesome, thank you both for the help, I greatly appreciate it. I didn't intend for you to write the code (just to push me in the right direction), but either way thanks! Commented Aug 7, 2014 at 21:51
  • 2
    There's no need to sum up the values each iteration; remove it from the for loop. For that matter, you can pass a generator expression directly into sum, a la summed = sum(row[0] for row in arcpy.da.SearchCursor(fc, 'QUANTITY_SOLID'))
    – Paul
    Commented Aug 7, 2014 at 22:14
  • 1
    Good call @Paul. Post updated to address comments.
    – Aaron
    Commented Aug 7, 2014 at 22:23

Your Answer

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

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