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
-
3Are you looking for a Python scripting solution or do you need to do this entirely in the field calculator?Aaron– Aaron ♦2014年08月07日 21:21:29 +00:00Commented 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.JumpInTheFire– JumpInTheFire2014年08月07日 21:32:44 +00:00Commented Aug 7, 2014 at 21:32
-
1I 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.Michael Stimson– Michael Stimson2014年08月07日 21:34:20 +00:00Commented Aug 7, 2014 at 21:34
1 Answer 1
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)
-
1I like that Aaron for the simplicity! Please note JumpinInTheFire that that is not a field calculator expression.Michael Stimson– Michael Stimson2014年08月07日 21:41:15 +00:00Commented Aug 7, 2014 at 21:41
-
1Awesome, 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!JumpInTheFire– JumpInTheFire2014年08月07日 21:51:49 +00:00Commented Aug 7, 2014 at 21:51
-
2There'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 intosum
, a lasummed = sum(row[0] for row in arcpy.da.SearchCursor(fc, 'QUANTITY_SOLID'))
Paul– Paul2014年08月07日 22:14:57 +00:00Commented Aug 7, 2014 at 22:14 -
1Good call @Paul. Post updated to address comments.2014年08月07日 22:23:58 +00:00Commented Aug 7, 2014 at 22:23