Thursday, 9 January 2020

arcpy - Calculate values from specific fields for each row in a featureclass


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'

Answer



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)

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...