0

I have a large script in which I now need to sum the values of a specific list of fields. I have a list of fields:

ave_fields = arcpy.ListFields(dg, "*Ave_STG*")

This list of fields may vary, hence why im using a list, and not explicit field names.

Now, all I need to do is sum the values in these fields for each row and return this value into another field ("weekly_ave").

Ive tried using SearchCursor:

with arcpy.da.SearchCursor(dg, ave_fields) as ucursor:
 total = 0
 for urow in ucursor:
 for i in range(0, len(ave_fields)):
 total += urow[i]
 print total

And ive also tried using NumpyArray to get this, but its not returning the right value:

tbl = [row[0] for row in arcpy.da.TableToNumPyArray(dg,ave_fields)]

This is my first attempt at using Numpy so I may not have got this right.

EDIT:

I have managed to get the numpy array to work properly, however i now need to return this value in the new field

tbl = arcpy.da.FeatureClassToNumPyArray(dg, ave_fields)
print sum(tbl[0]) # this allows me to sum a row within the array
#now i loop through each row and sum the values within the array, and return this value in the weekly_ave field for each row
with arcpy.da.UpdateCursor(dg, "Weekly_Ave") as ucursor:
 for urow in ucursor:
 print sum(tbl[0]) # this successfully sums the row, but i need to do this for all rows

I get the following error:

TypeError: unsupported operand type(s) for +: 'int' and 'numpy.ndarray'
asked Aug 7, 2017 at 8:55
2
  • Sum(urow) is enough, but instead of list of fields you'll need their names Commented Aug 7, 2017 at 10:07
  • Ive managed to get the array to work using ListFields method. However i cant loop through each row properly. Commented Aug 7, 2017 at 13:13

1 Answer 1

3

I'd add the weekly_ave field to your list of fields for your update cursor and then use indexing to sum and update your row accordingly.

ave_fields = [f.name for f in arcpy.ListFields(dg, "*Ave_STG*")]
with arcpy.da.UpdateCursor(dg, ave_fields + ["weekly_ave"]) as ucursor:
 for urow in ucursor:
 row [-1] = sum (row [:-1])
 ucursor.updateRow (row)
answered Aug 7, 2017 at 21:57
2
  • 1
    +1 however first row should produce field Names. [F.name for f in...] Commented Aug 7, 2017 at 22:04
  • @FelixIP good point. Updated. Commented Aug 7, 2017 at 22:10

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.