Skip to content

Instantly share code, notes, and snippets.

@nmpeterson
Last active December 20, 2015 10:39
Show Gist options
  • Save nmpeterson/6117002 to your computer and use it in GitHub Desktop.
Save nmpeterson/6117002 to your computer and use it in GitHub Desktop.
An arcpy-dependent function for ArcGIS 10.1+, which takes an input feature class (or layer) and the name of a weight field (e.g. population) from that feature class, and creates a new output feature class containing a single point feature at the average (weighted) coordinates of all of the input features.
def create_mean_centroid(in_layer, out_fc, weight_field):
'''
Calculate average coordinates from all input features' centroids,
weighted by values in weight_field.
Output is a new feature class containing a single mean centroid point.
It is *highly* recommended that a State Plane or UTM coordinate system
be used, as the calculations use Euclidean geometry.
'''
import os
import arcpy
freq = 0
sum_x = 0
sum_y = 0
with arcpy.da.SearchCursor(in_layer, ['SHAPE@TRUECENTROID', weight_field]) as cursor:
for coords, weight in cursor:
if weight:
freq += weight
sum_x += coords[0] * weight
sum_y += coords[1] * weight
mean_x = sum_x / freq
mean_y = sum_y / freq
mean_xy = (mean_x, mean_y)
in_desc = arcpy.Describe(in_layer)
in_sr = in_desc.spatialReference
arcpy.CreateFeatureclass_management(os.path.dirname(out_fc), os.path.basename(out_fc), 'POINT')
arcpy.DefineProjection_management(out_fc, in_sr)
with arcpy.da.InsertCursor(out_fc, ['SHAPE@XY']) as cursor:
cursor.insertRow([mean_xy])
return mean_xy
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment