[GIS] Understanding and using fieldmapping with ArcPy

appendarcpyfield-mapping

I'm having trouble trying to understand how fieldmapping works in ArcPy (I'm kinda new to Python). In the below example, I want to take a shapefile and append it to a feature class. But I want to use the field map parameter so the fields from the shapefile go to the correct field names in the feature class. So I successfully built this out in ModelBuilder and exported the Python script (see below). But so much of it doesn't make sense, for example…what are all these different codes… -1, 0, #, true, false, etc. And there seems to be no documentation anywhere online on the meaning behind these codes.

Does anybody know what these mean?

Also, I read that I can use the fieldmapping() class as a parameter in this script.

How would I even incorporate that?

If you know a much easier way (via python) to field map then using the above methods, I'm open to those suggestions.

Edit: The code below is only a simple test that I created, so I can hopefully understand fieldmapping better. But in the long run I want to this to be able to handle a LOT of fields from many different shapefiles.

Source shapefile schema: Name, Code, Date

Target feature class schema: Description, Num, Date

# Import arcpy module
import arcpy


# Local variables:
New_Shapefile_shp = "C:\\New_Shapefile.shp"
New_Featureclass__2_ = New_Shapefile_shp
New_Featureclass = "C:\\Target.gdb\\New_Featureclass"

# Process: Append
arcpy.Append_management("C:\\New_Shapefile.shp", New_Featureclass, "NO_TEST", "DESCRIPTION \"DESCRIPTION\" true true false 150 Text 0 0 ,First,#,C:\\New_Shapefile.shp,Name,-1,-1;NUM \"NUM\" true true false 4 Long 0 0 ,First,#,C:\\New_Shapefile.shp,Code,-1,-1;DATE \"DATE\" true true false 8 Date 0 0 ,First,#,C:\\New_Shapefile.shp,Date,-1,-1", "")

Best Answer

Another way of doing it using da.SearchCursor to read shapefile rows and insert them in the fc using da.InsertCursor:

import arcpy

shapefile = r'C:\folder\shapefile.shp'
fc = r'C:\data.gdb\featureclass'

#The position of the fields must match, Name=Description etc.
shapefields = ['Name','Code','Date']
fcfields = ['Description','Num','Date']

icur = arcpy.da.InsertCursor(fc, fcfields+['SHAPE@'])

with arcpy.da.SearchCursor(shapefile, shapefields+['SHAPE@']) as cursor:
    for row in cursor:
        icur.insertRow(row)

del icur
Related Question