I need to create a python script that sums a column's values in a table. Thereafter, the script is supposed to get the percentage of each individual row in that column and populate this percentage values in a another column. I been struggling for quite some time now, I checked the net, but there is nothing of this sort. The nearest is an ArcGIS Discussion Forum thread, but its for an older version of ArcMap, or I am using it wrong.

import arcgisscripting, sys
gp = arcgisscripting.create()

intable = sys.argv[1]
field = sys.argv[2]

# Create search cursor
rows = gp.SearchCursor(intable)
row = rows.Next()
x = 0.0
# Enter while loop for each feature/row
while row:
    x += row.getvalue(field)
    print x
    row = rows.next()
#note value can be rounded depending on field type
  • which version of arc are you using? The solution posted below uses the arcpy data access module which is only available from version 10.1 upwards. – Nxaunxau Jul 16 '14 at 12:39

try this:

ctotal = sum([row[0] for row in arcpy.da.SearchCursor("inputtable",["columnX","PercentColumn"])])#column total

with arcpy.da.UpdateCursor("inputtable",["columnX","PercentColumn"]) as cursor:
     for row in cursor:
         row[1] = (row[0]/float(ctotal))*100
  • Thank you, thank you so so much. It worked like a charm. I am new at this, can you please direct me to a link that can help me in learning as much python as possible. Especially that total line, that total was giving me trouble as in a for loop it would loose the value it retained initially. So when I use it in an equation, it would return the instantiated value of 0. I will await that link.. I am using arcmap10.1 by the way. – Lazlo Jul 17 '14 at 15:22
  • @Lazlo - refer to the list comprehension section from the python tutorial – Nxaunxau Jul 17 '14 at 21:24
  • Is it possible to nest the SeachCursor line within UpdateCursor? I am trying to create a tool that get a table as a parameter and calculate the previously stated. But when I use the SearchCursor outside of updateCursor, I get an error that states that the table does not exist. I am not sure if this is possible..your help would be appreciated greatly. – Lazlo Jul 18 '14 at 9:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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