I am very new to ModelBuilder + python.
I am trying to make a model. Don't know if it matters to upload it. If you want i can.
I want to calculate variance from a points-shapefile with elevation data and want to add this script to my model:
### x = (column: GRID_CODE, from a shapefile from model builder)
average = sum(x) / len(x)
variance = sum((average - value) ** 2 for value in x) / (len(x)-1)
### output to a new shapefile
How could i make this script working? Searched a lot here and at arcgis help but couldn't find something.
Can't understand how to "grab" data from shapefile, process them through script and then print the output.
1 Answer 1
if i understand the question - one way would be to use a SearchCursor - the cursor can vary slightly depending on your version of arcgis, but basically use the search cursor to total the value and calculate the average and variance. something similar to:
numberOfRows=0
total=0
data=[]
with arcpy.da.SearchCursor('yourshapefile.shp','GRID_CODE') as sCursor:
for row in sCursor:
total=row[0]+total
data.append(row[0])
numberOfRows+=1
ave=total/numberOfRows
you could then calculate the variance (using your equation)
var=sum([(ave-value)**2 for value in data])/(numberOfRows-1)
or typically numpy is also installed with arcgis, so you could import numpy as np and use
var=np.var(data)
which you could simply print to standard output.