Sunday, 12 November 2017

arcpy - How to SUM field and then insert into NULL column?


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



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)

No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...