# Is it possible to calculate statistics across multiple fields in arcpy?

The summary statistics command can be used in arcpy to calculate statistics - this tool runs against a single field, eg:

SUM—Adds the total value for the specified field.

Is there an out-of-the-box method to calculate statistics across multiple fields?

eg I'd like to calculate the MIN, MAX, MEAN and STDEV of Field1, Field2 and Field3, combined:

``````OID  Field1  Field2 Field3 Field4
1     23      24     25     26
2     12      13     14     15
3     17      18     19     20
``````

One approach is to read through the table with a cursor, and calculate these values manually in a script. Is there a better/faster way?

Edit: I need this to run on only the selected records, and these will change frequently.

Your best bet for this approach would definitely be a cursor. You can create a python tool that takes 2 inputs:

• Feature class/table in question
• multi-value parameter for all the fields you are interested in

The code to grab all this information is pretty straightforward:

``````import math, itertools, arcpy

FC = arcpy.GetParameterAsText(0)
fields = arcpy.GetParameterAsText(1).split(";")

#Flatten a list of lists
def flatten(list_lists):
return list(itertools.chain.from_iterable(list_lists))

#Whatever standard dev func is applicable
def std(x):
pass

#read values from fields and flatten
vals = flatten([r for r in row] for row in arcpy.da.SearchCursor(FC, fields))

arcpy.AddMessage("The MEAN is: {}\n".format(sum(vals) / len(vals)))
``````

If you want to dump the statistics to a table with a timestamp, that can be easily accomplished.

• the line `vals = flatten([r for r in row] for row...` is pure genius. Thanks! – Stephen Lead Aug 31 '14 at 23:25
• Great code, thank you ! I can calculate mean, but my STD is "none", which is not true in my data. Please, how can I alter the code for correct calculation of standard deviation? – maycca Jan 12 '18 at 17:16
• @maycca, you'd need to fill out the function `std`. – Paul Jan 16 '18 at 20:27

If there is, I do not know it, but if you are using an RDBMS then maybe a view or trigger can be used to maintain a field like that.

For a file geodatabase there are some ArcGIS Ideas that, if implemented, would make this easy for you:

for MIN, MAX and MEAN, you can use the summary statistics and compute the global values accross the fields using the field calculator (min is min of min, max is max of max and mean is mean of mean in this case). For the standard deviation, it is a bit more complicated but still possible based on the partitioning of the sum of squares.

``````Var_tot = ((n-1)*VAR_field1 + (n-1)*VAR_Field2 + (n-1)*VAR_Field3 + (n-1)*VAR_Field4 + n*n_f*Var(mean_Field1, mean_Field2,mean_Field3, mean_Field4) )/(n_f*n-1)
``````

where n is the number of rows, n_f the number of fields, and VAR_Field/Mean_Field come from the summary statistics.