Field Mappings - Multiple merge rules with a Spatial Join

I googled the title of this blog entry several ways and couldn't find any useful information so I wanted to post it here. I had the need to do a spatial join (in a script) but the tool in the toolbox doesn't give you the ability to get all the useful statistics (mean, max, min, sum, standard deviation) that you get by checking check-boxes doing a spatial join by right-clicking in the ArcMap table of contents.

I see that it can be done using field mappings and I used the example from the spatial join help documentation for ArcMap 10. It worked fine but I wanted to get more than one statistical result from a single field (tree DBH). I wanted the sum, mean, min, and max value but the example uses fieldmappings.replaceFieldMap. You can handle one field like this but if you do another one based on the same field, the “replace” in replaceFieldMap does what it implies.

I also found other fieldmapping samples on the internet but they are all for using merge or some other thing that also uses fieldmappings. I finally figured out that what I needed to do was use addFieldMap instead of replaceFieldMap so here it is step by step using replaceFieldMap for one (field2) and addField map for the second (field3).

#Field Mappings
fieldmappings = arcpy.FieldMappings()
fieldmappings.addTable(targetFeatures)
fieldmappings.addTable(joinFeatures)
DBHMeanIndex = fieldmappings.findFieldMapIndex("DBH")
WARDStdIndex = fieldmappings.findFieldMapIndex("WARD")
fieldmap = fieldmappings.getFieldMap(DBHMeanIndex)
fieldmap2 = arcpy.FieldMap()
fieldmap3 = fieldmappings.getFieldMap(WARDStdIndex)
# fieldmap2.addInputField
fieldmap2.addInputField(joinFeatures, "DBH")
# Get the output field's properties as a field object
field = fieldmap.outputField
field2 = fieldmap2.outputField
field3 = fieldmap3.outputField
# Rename the field and pass the updated field object back into the field map
field.name = "mean_dbh"
field2.name = "sum_dbh"
field3.name = "std_ward"
field.aliasName = "mean_dbh"
field2.aliasName = "sum_dbh"
field3.aliasName = "std_ward"
fieldmap.outputField = field
fieldmap2.outputField = field2
fieldmap3.outputField = field3
# Set the merge rule to mean and then replace the old fieldmap in the mappings object
# with the updated one
fieldmap.mergeRule = "Mean"
fieldmap2.mergeRule = "Sum"
fieldmap3.mergeRule = "StdDev"
fieldmappings.replaceFieldMap(DBHMeanIndex, fieldmap)
fieldmappings.addFieldMap(fieldmap2)
fieldmappings.replaceFieldMap(WARDStdIndex, fieldmap3)
arcpy.SpatialJoin_analysis(targetFeatures, joinFeatures, outputFC, "#", "#", fieldmappings)