I would like to calculate a mean and STD for one field in my feature class. I am python beginner.
I have found great source calcualting mean and STD for multiple fields, however, the STD calculation seems not correct: Is it possible to calculate statistics across multiple fields in arcpy? After applying the code, my STD is "None" which is not true for real data.
My code:
import math, itertools, arcpy
FC = arcpy.GetParameterAsText(0)
field = "RASTERVALU"
#Flatten a list of lists # do I even need this if I have just one field? How to replace this?
def flatten(list_lists):
return list(itertools.chain.from_iterable(list_lists))
#Definition of standard deviation, seems not working...
def std(x):
pass
#read values from fields and flatten
vals = flatten([r for r in row] for row in arcpy.da.SearchCursor(FC, field))
# print results
print "mean is " + str(sum(vals) / len(vals))
print "std is" + str(std(vals)) # STD gives back None
How to correctly calculate my STD? I need it to save as a value, which I can use further in the code.
1 Answer 1
Your definition of the std()
function is just to pass
through the dataset and not to calculate anything. If you want to define it as a function, you need to tell the function what to calculate. While you could write the function to calculate standard deviation, my suggestion would be to utilize the numpy module, which has a mean and stdev function among many other things.
Add to your import statements:
import numpy as np
and then you can use str(np.mean(vals))
and str(np.std(vals))
as parts of the print statement. Also note that np.std returns the population standard deviation (divisor is N) and not the sample stdev (divisor is N-1). You can change this by changing the code to str(np.std(vals, ddof=1))
.
-
Thank you !! seems right for STD calculation! Please, any advice if I need to "Flatten a list of lists" if I am using only one field in the table? How can I replace it?maycca– maycca2018年01月12日 18:15:56 +00:00Commented Jan 12, 2018 at 18:15