I am looking for a script that will calculate the cumulative sum of say population (based on a presorted table that I have created) as long as the variable of ID is the same. So it might look like
ID | POP | CUMPOP |
---|---|---|
1 | 100 | 100 |
1 | 250 | 350 |
1 | 150 | 500 |
2 | 100 | 100 |
2 | 500 | 600 |
3 | 150 | 150 |
3 | 600 | 750 |
3 | 100 | 850 |
3 | 150 | 1000 |
this:
Solved! Go to Solution.
Hi Clinton,
Try the following:
import arcpy from arcpy import env env.workspace = r"E:\Temp\Python\test.gdb" table = "Sample" list = [] #append IDs to list with arcpy.da.SearchCursor(table, ["ID"]) as cursor: for row in cursor: list.append(row[0]) del cursor #remove duplicates list = set(list) #update CUMPOP field for id in list: with arcpy.da.UpdateCursor(table, ["POP", "CUMPOP"], "ID = {0}".format(id)) as cursor: firstTime = True for row in cursor: if firstTime: row[1] = row[0] cursor.updateRow(row) newVal = row[0] firstTime = False else: print newVal row[1] = row[0] + newVal cursor.updateRow(row) newVal = row[0] del cursor
Try the Dissolve—Help | ArcGIS for Desktop tool. You could dissolve based on ID and sum on either or both of your pop fields
Hi Clinton,
Try the following:
import arcpy from arcpy import env env.workspace = r"E:\Temp\Python\test.gdb" table = "Sample" list = [] #append IDs to list with arcpy.da.SearchCursor(table, ["ID"]) as cursor: for row in cursor: list.append(row[0]) del cursor #remove duplicates list = set(list) #update CUMPOP field for id in list: with arcpy.da.UpdateCursor(table, ["POP", "CUMPOP"], "ID = {0}".format(id)) as cursor: firstTime = True for row in cursor: if firstTime: row[1] = row[0] cursor.updateRow(row) newVal = row[0] firstTime = False else: print newVal row[1] = row[0] + newVal cursor.updateRow(row) newVal = row[0] del cursor
Thank you, this works perfectly!!
just for reference, I found one issue in line 33:
newVal = row[0]
Should be:
newVal = row[1]
Well I need the running cumulative average. After I run this loop, I need to be able to remove or select all the rows with a value greater than or less than a certain value that I choose for my analysis.