I am using
arcpy to merge multiple feature classes from a list of feature classes. They all have the same fields. Let's say they all have the
fields = ['CO_FIPS', 'MILES', 'FLOOD_ZONE', 'VALID', 'REGION']. However, I only want to include 'CO_FIPS', 'MILES', and 'FLOOD_ZONE' in the output merged feature class. It seems I need to use
field mapping to limit the fields in my output, but I am not 100% how to do that:
working_dir = r"C:\Projects\MyProj\stream_lines.gdb" arcpy.env.workspace = working_dir s_studies_for_merge = ['stream1', 'stream2', 'stream3', ... 'stream10'] fieldMappings = arcpy.FieldMappings() merged_output = os.path.join(working_dir, "AllStreams") fieldMappings.addTable('stream1') for field in fieldMappings.fields: if field.name not in ['CO_FIPS', 'MILES', 'FLOOD_ZONE']: fieldMappings.removeFieldMap(fieldMappings.findFieldMapIndex(field.name)) arcpy.Merge_management(s_studies_for_merge, merged_output, fieldMappings)
My confusion is mainly that most examples show only 2 features being merged and that the mapping involves settings that I don't need for certain fields. I only want to exclude the fields I don't want and keep the fields I do. What do I need to do here?
I tried applying the below answer(@geodranic) this way (assuming I needed to iterate and add field mapping for each of the 10 feature classes in my
mappings = arcpy.FieldMappings() fields = ['REACH_ID', 'STUDY_ID', 'CID', 'FLD_ZONE', 'VALIDATION_STATUS', 'STATUS_TYP', 'MILES', 'STATUS_DATE', 'STUDY_TYPE', 'LINE_TYPE', 'BS_ZONE', 'BS_STDYTYP', 'PRELIM_DATE'] for item in s_studies_for_merge: print(item) for field in fields: print(field) map = arcpy.FieldMap() map.addInputField(item, field) arcpy.Merge_management(s_studies_for_merge, s_studs, mappings)
I got an error that the merge failed because of one of the fields I didn't want included in the merge:
ExecuteError: ERROR 001156: Failed on input OID 1, could not write value 'VIII' to output field FEMA_Region Failed to execute (Merge)
How can I apply this correctly?