Calculate a mean value from a field

Here’s a function to return a mean value from a field by taking advantage of the Summary Statistics tool.

This code is supported in ArcGIS 10.0:

def calculate_mean_value(table, field):
    stats_table = r"in_memory\stats"
    arcpy.Statistics_analysis(table, stats_table, [[field, "MEAN"]])
    mean_field = "MEAN_{0}".format(field)
    cursor = arcpy.SearchCursor(stats_table, "", "", mean_field)
    row = cursor.next()
    mean_value = row.getValue(mean_field)
    del cursor
    return mean_value

 

ArcGIS 10.1 introduces a new data access module, arcpy.da, for working with data. It includes functions for converting tables and feature classes to and from NumPy arrays, as well as, cursor functions which provide improved cursor support and faster performance. The following code can replace the previous sample code when using ArcGIS 10.1.

From more information about arcpy.da, see the data access module.

def calculate_mean_value(table, field):
    na = arcpy.da.TableToNumPyArray(table, field)
    return numpy.mean(na[field])
Advertisements