[GIS] Spatial Join Field Mapping in ArcPy

arcpyfield-mappingspatial-join

I know there already are posts about this subject, I tried to derive a solution for my own problem but the code for field mapping is very complex to me.

I have a Raster 100x100m and point layers that I want to join using a python script. I need the SUM of a field called "weight" (point layer) added to the grid, but I don't know how to define the field mapping.

So far the script looks like this (but doesn't sum up my weight field):

import arcpy
from arcpy import env

env.workspace = r"C:\Users\Daniela\Desktop\test"

fc_list = arcpy.ListFeatureClasses()

for fc in fc_list:
    arcpy.SpatialJoin_analysis("grid100.shp",fc,"C:/Users/Daniela/Desktop/test/test" + "_" + str(fc),"JOIN_ONE_TO_ONE","KEEP_ALL","sum","INTERSECT","","")

Best Answer

Field mappings are kind of cumbersome in ArcGIS. First you create a fieldmappings object, then create fieldmap, then add input fields and define output fields. Also, you can add the entire table to the mapping like:

    myMapping = arcpy.FieldMappings()
    myMapping.addTable(path_to_the_table)
    arcpy.Append_management(fc, fc_out, "NO_TEST", myMapping)

I found the following example that I used some time ago when building custom mappings:

in_file1 = 'data.gdb/Trees'
in_file2 = 'Plants.shp'
output_file = 'data.gdb/Vegetation'

# Create the required FieldMap and FieldMappings objects.
fm_type = arcpy.FieldMap()
fm_diam = arcpy.FieldMap()
fms = arcpy.FieldMappings()

# Get the field names of vegetation type and diameter for both original files.
tree_type = "Tree_Type"
plant_type = "Plant_Type"

tree_diam = "Tree_Diameter"
plant_diam = "Diameter"

# Add fields to their corresponding FieldMap objects.
fm_type.addInputField(in_file1, tree_type)
fm_type.addInputField(in_file2, plant_type)

fm_diam.addInputField(in_file1, tree_diam)
fm_diam.addInputField(in_file2, plant_diam)

# Set the output field properties for both FieldMap objects.
type_name = fm_type.outputField
type_name.name = 'Veg_Type'
fm_type.outputField = type_name

diam_name = fm_diam.outputField
diam_name.name = 'Veg_Diam'
fm_diam.outputField = diam_name

# Add the FieldMap objects to the FieldMappings object.
fms.addFieldMap(fm_type)
fms.addFieldMap(fm_diam)

# Merge the two feature classes.
arcpy.Merge_management([in_file1, in_file2], output_file, fms)