Asignar campos de entrada a campos de salida

Una tarea de geoprocesamiento común consiste en combinar muchos datasets en un dataset nuevo o existente, para crear un dataset único que cubra un área mayor o una tabla que contenga un número de registros mayor. A menudo, los atributos o campos son los mismos para todas las entradas que se utilizan en una operación de combinación o anexión; a veces, sin embargo, no coinciden, y es necesario asignar relaciones entre campos de nombres y tipos diferentes. Para ver un ejemplo de asignaciones de campos, consulte la herramienta Fusionar; facilita esta asignación de relaciones de forma que los datos se coloquen en los campos de salida deseados y con los valores correctos.

FieldMap

The FieldMap object provides a field definition and a list of input fields from a set of tables or feature classes that provide its values.

The properties of the FieldMap object include the start and end position of an input text value, so an output value can be created using a slice of an input value. If a FieldMap object contains multiple input fields from the same table or feature class, each record's values are merged using the mergeRule property. This is a convenient way to join values, such as a street name that is held in one field and a street type that is held in another, for example, Eureka and Street. The joinDelimiter property of the FieldMap object is used when Join is specified as the mergeRule value. Any set of characters, such as a space, can be used as a delimiter. In the example above, this would create a value of Eureka Street.

FieldMappings

The FieldMappings object is a collection of FieldMap objects, and it is used as the parameter value for tools that perform field mapping, such as Merge. The easiest way to work with these objects is to first create a FieldMappings object, then initialize its FieldMap objects by adding the input feature classes or tables that are to be combined. Once all inputs are provided, the FieldMappings object will contain one FieldMap object, or output field, for each unique field name from all the inputs. You can modify this list by adding new fields, altering the properties or contents of an output field, or removing unwanted output fields.

Ejemplos

En el siguiente ejemplo, varias clases de entidad que contienen datos del censo de EE.UU. se combinan para formar una nueva clase de entidad. Uno de los atributos de entrada que se encuentra en todas las entradas es un campo numérico, STFID. Este valor de 15 dígitos es un identificador único para todos los bloques censales de Estados Unidos. El valor se puede dividir en cuatro componentes. Los primeros dos dígitos proporcionan el código del estado, los tres siguientes indican el condado, los seis siguientes identifican el distrito censal y los últimos cuatro identifican el bloque censal. El valor 360899912001006 representa el bloque censal (1006) que contiene la Universidad Estatal de Nueva York en Potsdam, en el norte del estado de Nueva York (36), dentro del distrito censal 991200 del condado de St. Lawrence (089). La muestra de script fusionará estas clases de entidad y, además, creará dos campos (TRACTID y BLOCKID), ya que los datos de entrada solo tienen el atributo STFID. Para ello, se inicializa el objeto FieldMappings utilizando el método addTable para introducir cada entrada. Después, se modifica el objeto FieldMappings predeterminado creando dos objetos FieldMap, rellenando sus propiedades y agregándolos al objeto FieldMappings.

import arcpy

arcpy.env.workspace = "C:/Data/CityBlocks.gdb"
outfc = "C:/Data/CityBlocks.gdb/AllBlocks"

# Each of the input Feature classes has an STFID, which is the combination of 
# the Tract ID and Block ID for each block. Separate these values out from this 
# field into two new fields, TRACTID and BLOCKID.

# Create a fieldmappings and two new fieldmaps.
fieldmappings = arcpy.FieldMappings()
fldmap_TRACTID = arcpy.FieldMap()
fldmap_BLOCKID = arcpy.FieldMap()

# List all the feature classes in the workspace that start with 'block' in 
# their name and are of polygon feature type.
fcs = arcpy.ListFeatureClasses("block*", "Polygon")

# Create a value table that will hold the input feature classes to Merge
vTab = arcpy.ValueTable()
for fc in fcs:
    # Adding a table is the fast way to load all the fields from the input 
    # into fieldmaps held by the fieldmappings object.
    fieldmappings.addTable(fc)

    # In this example also create two fieldmaps by 'chopping up' an input field. 
    # Feed the chopped field into the new fieldmaps.
    fldmap_TRACTID.addInputField(fc, "STFID")
    fldmap_BLOCKID.addInputField(fc, "STFID")

    # Populate the input value table with feature classes
    vTab.addRow(fc)

# Set the starting and ending position of the fields going into the TractID 
# fieldmap. This is the location in the STFID field where the TractID falls.
for x in range(0, fldmap_TRACTID.inputFieldCount):
    fldmap_TRACTID.setStartTextPosition(x, 5)
    fldmap_TRACTID.setEndTextPosition(x, 10)

# Set the Name of the Field output from this field map.
fld_TRACTID = fldmap_TRACTID.outputField
fld_TRACTID.name = "TRACTID"
fldmap_TRACTID.outputField = fld_TRACTID

# Set the starting and ending position of the fields going into the BlockID 
# fieldmap. This is the location in the STFID field where the blockID falls.
for x in range(0, fldmap_BLOCKID.inputFieldCount):
    fldmap_BLOCKID.setStartTextPosition(x, 11)
    fldmap_BLOCKID.setEndTextPosition(x, 16)

# Set the Name of the Field output from this field map.
fld_BLOCKID = fldmap_BLOCKID.outputField
fld_BLOCKID.name = "BLOCKID"
fldmap_BLOCKID.outputField = fld_BLOCKID

# Add the custom fieldmaps into the fieldmappings object.
fieldmappings.addFieldMap(fldmap_TRACTID)
fieldmappings.addFieldMap(fldmap_BLOCKID)

# Run the Merge tool.
arcpy.Merge_management(vTab, outfc, fieldmappings)

El siguiente ejemplo muestra cómo modificar un objeto FieldMap después de haberlo creado utilizando el método addTable del objeto FieldMappings. Esto es importante cuando las entradas tienen campos con nombres diferentes pero que lógicamente contienen los mismos valores.

import arcpy

outfc = "C:/data/CityData.gdb/AllBlocks"

# Want to merge these two feature classes together. Have a field that has the 
# same content but the names are slightly different: Blocks1 has TRACT2000 
# and Blocks2 TRACTCODE. Name the output the same as Blocks1.
fc1 = "C:/data/CityData.gdb/Blocks1"
fc2 = "C:/data/CityData.gdb/Blocks2"

# Create a new fieldmappings and add the two input feature classes.
fieldmappings = arcpy.FieldMappings()
fieldmappings.addTable(fc1)
fieldmappings.addTable(fc2)

# First get the TRACT2000 fieldmap. Then add the TRACTCODE field from Blocks2 
# as an input field. Then replace the fieldmap within the fieldmappings object.
fieldmap = fieldmappings.getFieldMap(fieldmappings.findFieldMapIndex("TRACT2000"))
fieldmap.addInputField(fc2, "TRACTCODE")
fieldmappings.replaceFieldMap(fieldmappings.findFieldMapIndex("TRACT2000"), fieldmap)

# Remove the TRACTCODE fieldmap.
fieldmappings.removeFieldMap(fieldmappings.findFieldMapIndex("TRACTCODE"))

# Run the Merge tool.
arcpy.Merge_management([fc1, fc2], outfc, fieldmappings)