4

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","","")

1 Answer 1

6

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)
1
  • thanks for the help! I have to admit, I still don't totally understand field mappings, but it worked anyway! :) Commented Oct 7, 2015 at 12:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.