UpdateCursor

Resumen

UpdateCursor establece acceso de lectura y escritura a los registros devueltos de una tabla o clase de entidad.

Devuelve un iterador de listas. El orden de los valores en la lista coincide con el orden de los campos especificados por el argumento field_names.

Debate

Es posible iterar los cursores de actualización mediante un bucle for. Los cursores de actualización también admiten sentencias with para restablecer la iteración y ayudar en la eliminación de bloqueos. Sin embargo, se debería tener en cuenta el utilizar una sentencia del para eliminar el objeto o ajustar el cursor en una función para que el objeto de cursor quede fuera del alcance, a fin de protegerse contra todos los casos de bloqueo.

En Python 2, UpdateCursor admite el método next de iteración para recuperar la siguiente fila fuera de un bucle. En Python 3, se realiza lo equivalente mediante la función next integrada de Python.

Nota:

La apertura de operaciones de inserción o actualización simultáneas en el mismo espacio de trabajo con distintos cursores requiere que se inice una sesión de edición.

Nota:

Utilizar UpdateCursor en datos versionados requiere que se inice una sesión de edición.

Nota:

Las herramientas Calcular campo y Calcular campos también se pueden utilizar para actualizar valores de campo.

Sintaxis

UpdateCursor (in_table, field_names, {where_clause}, {spatial_reference}, {explode_to_points}, {sql_clause}, {datum_transformation})
ParámetroExplicaciónTipo de datos
in_table

The feature class, layer, table, or table view.

String
field_names
[field_names,...]

A list (or tuple) of field names. For a single field, you can use a string instead of a list of strings.

Use an asterisk (*) instead of a list of fields to access all fields from the input table (raster and BLOB fields are excluded). However, for faster performance and reliable field order, it is recommended that the list of fields be narrowed to only those that are actually needed.

Raster fields are not supported.

Additional information can be accessed using tokens (such as OID@) in place of field names:

  • SHAPE@XYA tuple of the feature's centroid x,y coordinates.
  • SHAPE@XYZA tuple of the feature's centroid x,y,z coordinates.
  • SHAPE@TRUECENTROIDA tuple of the feature's centroid x,y coordinates. This returns the same value as SHAPE@XY.
  • SHAPE@XA double of the feature's x-coordinate.
  • SHAPE@YA double of the feature's y-coordinate.
  • SHAPE@ZA double of the feature's z-coordinate.
  • SHAPE@MA double of the feature's m-value.
  • SHAPE@JSON The Esri JSON string representing the geometry.
  • SHAPE@WKBThe well-known binary (WKB) representation for OGC geometry. It provides a portable representation of a geometry value as a contiguous stream of bytes.
  • SHAPE@WKTThe well-known text (WKT) representation for OGC geometry. It provides a portable representation of a geometry value as a text string.
  • SHAPE@A geometry object for the feature.
  • SHAPE@AREAA double of the feature's area.
  • SHAPE@LENGTHA double of the feature's length.
  • OID@The value of the Object ID field.
String
where_clause

An optional expression that limits the records returned. For more information on WHERE clauses and SQL statements, see SQL reference for query expressions used in ArcGIS.

(El valor predeterminado es None)

String
spatial_reference

The spatial reference of the feature class. When this argument is specified, the feature will be projected (or transformed) from the input's spatial reference. If unspecified, the input feature classes' spatial reference will be used. Valid values for this argument are a SpatialReference object or string equivalent.

(El valor predeterminado es None)

SpatialReference
explode_to_points

Deconstruct a feature into its individual points or vertices. If explode_to_points is set to True, a multipoint feature with five points, for example, is represented by five rows.

(El valor predeterminado es False)

Boolean
sql_clause

An optional pair of SQL prefix and postfix clauses organized in a list or tuple.

An SQL prefix clause supports None, DISTINCT, and TOP. An SQL postfix clause supports None, ORDER BY, and GROUP BY.

An SQL prefix clause is positioned in the first position and will be inserted between the SELECT keyword and the SELECT COLUMN LIST. The SQL prefix clause is most commonly used for clauses such as DISTINCT or ALL.

An SQL postfix clause is positioned in the second position and will be appended to the SELECT statement, following the where clause. The SQL postfix clause is most commonly used for clauses such as ORDER BY.

Nota:

DISTINCT, ORDER BY, and ALL are only supported when working with databases. They are not supported by other data sources (such as dBASE or INFO tables).

TOP is only supported by SQL Server databases.

(El valor predeterminado es (None, None))

tuple
datum_transformation

When the cursor projects the features from one spatial reference to another, if the spatial references do not share the same datum, an appropriate datum transformation should be specified.

An update cursor can perform a projection or transformation at two stages: when reading the features from the feature class on disk, and when writing the updated features into the feature class.

The ListTransformations function can be used to provide a list of valid datum transformations between two spatial references.

Learn more about datum transformations

String

Propiedades

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

A tuple of field names used by the cursor.

The tuple will include all fields (and tokens) specified by the field_names argument. If the field_names argument is set to *, the fields property will include all fields used by the cursor. When using *, geometry values will be returned in a tuple of the x,y-coordinates (equivalent to the SHAPE@XY token).

The order of the field names on the fields property will be the same as passed in with the field_names argument.

tuple

Descripción general del método

MétodoExplicación
deleteRow ()

Deletes the current row.

reset ()

Resets the cursor back to the first row.

updateRow (row)

Updates the current row in the table.

Métodos

deleteRow ()
reset ()
updateRow (row)
ParámetroExplicaciónTipo de datos
row

A list or tuple of values. The order of values should be in the same order as the fields.

When updating fields, if the incoming values match the type of field, the values will be cast as necessary. For example, a value of 1.0 to a string field will be added as "1.0", and a value of "25" added to a float field will be added as 25.0.

tuple

Muestra de código

Ejemplo 1 de UpdateCursor

Use UpdateCursor para actualizar un valor de campo evaluando los valores de otros campos.

import arcpy

fc = 'c:/data/base.gdb/well'
fields = ['WELL_YIELD', 'WELL_CLASS']

# Create update cursor for feature class 
with arcpy.da.UpdateCursor(fc, fields) as cursor:
    # For each row, evaluate the WELL_YIELD value (index position 
    # of 0), and update WELL_CLASS (index position of 1)
    for row in cursor:
        if (row[0] >= 0 and row[0] <= 10):
            row[1] = 1
        elif (row[0] > 10 and row[0] <= 20):
            row[1] = 2
        elif (row[0] > 20 and row[0] <= 30):
            row[1] = 3
        elif (row[0] > 30):
            row[1] = 4

        # Update the cursor with the updated list
        cursor.updateRow(row)
Ejemplo 2 de UpdateCursor

Use UpdateCursor para actualizar un campo de distancias de zona de influencia para su uso con la herramienta Zona de influencia.

import arcpy

arcpy.env.workspace = 'c:/data/output.gdb'
fc = 'c:/data/base.gdb/roads'
fields = ['ROAD_TYPE', 'BUFFER_DISTANCE']

# Create update cursor for feature class 
with arcpy.da.UpdateCursor(fc, fields) as cursor:
    # Update the field used in Buffer so the distance is based on road 
    # type. Road type is either 1, 2, 3, or 4. Distance is in meters. 
    for row in cursor:
        # Update the BUFFER_DISTANCE field to be 100 times the 
        # ROAD_TYPE field.
        row[1] = row[0] * 100
        cursor.updateRow(row) 

# Buffer feature class using updated field values
arcpy.Buffer_analysis(fc, 'roads_buffer', 'BUFFER_DISTANCE')

Temas relacionados