FieldMappings

Resumen

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.

Debate

Las propiedades del objeto FieldMap incluyen las posiciones inicial y final de un valor de texto de entrada, de tal forma que se pueda crear un valor de salida utilizando una porción de un valor de entrada. Si un objeto FieldMap contiene varios campos de entrada de la misma tabla o clase de entidad, los valores de cada registro se fusionan con la propiedad mergeRule. Ésta es una manera conveniente de unir valores, tales como un nombre de calle contenido en un campo y un tipo de calle contenido en otro, por ejemplo, Eureka y Street. La propiedad joinDelimiter de FieldMap se utiliza si se especifica el valor Join de mergeRule. Cualquier conjunto de caracteres, tal como un espacio, se puede utilizar como delimitador. En el ejemplo anterior, esto crearía el valor Eureka Street.

El objeto FieldMappings es una colección de objetos FieldMap y se utiliza como el valor de parámetro en las herramientas que realizan asignación de campos, por ejemplo, Fusionar. La forma más fácil de trabajar con estos objetos consiste en crear primero un objeto FieldMappings y, después, inicializar sus objetos FieldMap agregando las tablas o clases de entidad de entrada que se deben combinar. Una vez proporcionadas todas las entradas, el objeto FieldMappings contendrá un objeto FieldMap, o campo de salida, para cada nombre de campo único de todas las entradas. Puede modificar esta lista agregando campos nuevos, modificando las propiedades o el contenido de un campo de salida o quitando los campos de salida no deseados.

Sintaxis

 FieldMappings  ()

Propiedades

PropiedadExplicaciónTipo de datos
fieldCount
(Sólo lectura)

The number of output fields.

Integer
fieldMappings
(Lectura y escritura)

A list of FieldMap objects that make up the FieldMappings object.

FieldMap
fieldValidationWorkspace
(Lectura y escritura)

The workspace type that defines the rules for attribute field naming. These rules are used when determining the output field names, which are based on the names of the input fields. For example, setting the fieldValidationWorkspace property to the path of a folder on disk containing the input shapefiles will result in the output field names being truncated to 10 characters. Setting the fieldValidationWorkspace property to the path of a file geodatabase will allow for much longer field names. The fieldValidationWorkspace property should be set with a consideration for the output format.

String
fields
(Sólo lectura)

A list of Field objects. Each field object represents the properties of each output field.

Field

Descripción general del método

MétodoExplicación
addFieldMap (field_map)

Add a field map to the field mappings.

addTable (table_dataset)

Adds a table to the field mappings object.

exportToString ()

Exports the object to its string representation.

findFieldMapIndex (field_map_name)

Find a field map within the field mappings by name.

getFieldMap (index)

Returns a FieldMap object from the FieldMappings object by index position.

loadFromString (string)

Defines a FieldMappings object from a formatted string.

removeAll ()

Removes all values and creates an empty object.

removeFieldMap (index)

Removes a FieldMap object from the FieldMappings object.

replaceFieldMap (index, value)

Replace a FieldMap object within the FieldMappings object.

Métodos

addFieldMap (field_map)
ParámetroExplicaciónTipo de datos
field_map

The field map to add to the field mappings

FieldMap
addTable (table_dataset)
ParámetroExplicaciónTipo de datos
table_dataset

The table to add to the field mappings object.

String
exportToString ()
Valor de retorno
Tipo de datosExplicación
String

The WKT string representation of the object.

findFieldMapIndex (field_map_name)
ParámetroExplicaciónTipo de datos
field_map_name

Find the field map by name.

String
Valor de retorno
Tipo de datosExplicación
Integer

The index position of the field map.

getFieldMap (index)
ParámetroExplicaciónTipo de datos
index

The index position of the FieldMap object.

Integer
Valor de retorno
Tipo de datosExplicación
FieldMap

The FieldMap object from the FieldMappings object.

loadFromString (string)
ParámetroExplicaciónTipo de datos
string

The string representation of the object.

In addition to FieldMappings and FieldMap methods and properties, you can also construct a FieldMappings object from a formatted string.

The following example shows the creation of a FieldMappings object that could be used with the Merge tool.

import arcpy

fieldmappings_string = 'REGION "Region" true true false 21 Text -1 -1,First,#,c:\\data\\fgdb.gdb\\north_america,REGION,-1,-1,c:\\data\\fgdb.gdb\\south_america,REGION2,-1,-1'

fieldmappings = arcpy.FieldMappings()
fieldmappings.loadFromString(fieldmappings_string)

The first nine values in the string define an output field and are space delimited.

  • The name of the output field.
  • The alias of the output field.
  • Whether the output field is editable (true or false).
  • Whether the output field supports nulls (true or false).
  • Whether the output field is required (true or false).
  • The length of the output field (text fields only).
  • The field type of the output field.
  • The precision of the output field (float and double fields only).
  • The scale of the output field (float and double fields only).

The remaining values define the field map characteristics and are comma delimited.

  • The field map merge rule.
  • The concatenator to join values.
  • The path to the input table.
  • The field name from the input table.
  • The start position of an input text value.
  • The end position of an input text value.

Any number of input fields can be mapped to the output field, not only two, as implied in the example. Include the merge rule and concatenator once, and include the dataset path, field name, and start position and end position for each input field.

Enclose any values with spaces, such as the field alias or concatenator, in quotation marks.

To skip a value, use a # for string values, and -1 for numeric values.

As shown in the following example, use a semicolon delimiter to separate multiple output fields.

import arcpy

fieldmappings_string = 'REGION "Region" true true false 21 Text -1 -1,First,#,c:\\data\\fgdb.gdb\\north_america,REGION,-1,-1,c:\\data\\fgdb.gdb\\south_america,REGION2,-1,-1;CAPITAL "Capital" true true false 21 Text -1 -1,First,#,c:\\data\\fgdb.gdb\\north_america,CAPITAL,-1,-1,c:\\data\\fgdb.gdb\\south_america,CAPITAL2,-1,-1'

fieldmappings = arcpy.FieldMappings()
fieldmappings.loadFromString(fieldmappings_string)
String
removeAll ()
removeFieldMap (index)
ParámetroExplicaciónTipo de datos
index

The index position of the FieldMap.

Integer
replaceFieldMap (index, value)
ParámetroExplicaciónTipo de datos
index

The index position of the FieldMap object to be replaced.

Integer
value

The replacement FieldMap object.

FieldMap

Muestra de código

FieldMappings example

A menudo, los objetos FieldMap se utilizan para fusionar datasets similares en un solo dataset que englobe todo. En este ejemplo, la clase de entidad Trees y el shapefile Plants.shp se fusionan en una sola clase de entidad: Vegetation. Ambas clases de entidad originales tienen dos atributos: Type y Diameter. Estos dos atributos se deben mantener en toda la fusión.

import arcpy
# Set the workspace
arcpy.env.workspace = 'c:/base'
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)
FieldMappings example 2

Este ejemplo muestra la opción de utilizar objetos FieldMap para fusionar campos, a través de la herramienta FeatureClassToFeatureClass. En este ejemplo, una clase de entidad contiene información sobre el número de accidentes por intersección que se producen en una ciudad. Cada año de datos se conserva en un campo. El usuario desea encontrar el promedio de accidentes en cada intersección, sin modificar la tabla existente.

import arcpy
# Set the workspace arcpy.env.workspace = 'c:/base/data.gdb'
in_file = 'AccidentData' out_file = 'AverageAccidents'
# Create the necessary FieldMap and FieldMappings objects fm = arcpy.FieldMap() fm1 = arcpy.FieldMap() fms = arcpy.FieldMappings()
# Each field with accident data begins with 'Yr' (from Yr2007 to Yr2012). # The next step loops through each of the fields beginning with 'Yr', # and adds them to the FieldMap Object for field in arcpy.ListFields(in_file, 'Yr*'):
    fm.addInputField(in_file, field.name)
# Set the merge rule to find the mean value of all fields in the
# FieldMap object fm.mergeRule = 'Mean'
# Set properties of the output name. f_name = fm.outputField f_name.name = 'AvgAccidents' f_name.aliasName = 'AvgAccidents' fm.outputField = f_name
# Add the intersection field to the second FieldMap object fm1.addInputField(in_file, "Intersection")
# Add both FieldMaps to the FieldMappings Object fms.addFieldMap(fm) fms.addFieldMap(fm1)
# Create the output feature class, using the FieldMappings object arcpy.FeatureClassToFeatureClass_conversion(    in_file, arcpy.env.workspace, out_file, field_mapping=fms)

Temas relacionados