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])

2 thoughts on “Calculate a mean value from a field

  1. Pingback: Dueling: Calculate a mean value from a field « Thiiink: Ideas, Imagination, and Innovation in GIS

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s