UpdateCursor

Zusammenfassung

UpdateCursor establishes read-write access to records returned from a feature class or table.

Returns an iterator of lists. The order of values in the list matches the order of fields specified by the field_names argument.

Learn more about data access using cursors

Diskussion

Update cursors can be iterated using a for loop. Update cursors also support with statements to reset iteration and aid in removal of locks. However, using a del statement to delete the object or wrapping the cursor in a function to have the cursor object go out of scope should be considered to guard against all locking cases.

Beim Öffnen von gleichzeitigen Einfüge- oder Aktualisierungsoperationen in demselben Workspace unter Verwendung unterschiedlicher Cursors muss eine Editiersitzung gestartet werden.

Nachstehend sind einige Dataset-Typen aufgeführt, die nur innerhalb einer Editiersitzung bearbeitet werden können:

  • Feature-Classes, die Teil einer Topologie sind
  • Feature-Classes, die an einem geometrischen Netzwerk beteiligt sind
  • Feature-Classes, die Teil eines Netzwerk-Datasets sind
  • Versionierte Datasets in Enterprise-Geodatabases
  • Einige Objekte und Feature-Classes mit Klassenerweiterungen

In Python 2, UpdateCursor supports the iterator next method to retrieve the next row outside of a loop. In Python 3, the equivalent is performed by using the Python built-in next function.

Hinweis:

The Calculate Field and Calculate Fields tools can also be used to update field values.

Hinweis:

Using an UpdateCursor on a layer with a joined table is not supported.

Syntax

UpdateCursor (in_table, field_names, {where_clause}, {spatial_reference}, {explode_to_points}, {sql_clause}, {datum_transformation}, {explicit}, {spatial_filter}, {spatial_relationship}, {search_order})
ParameterErläuterungDatentyp
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 (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@XYEin Tupel von XY-Koordinaten für den Feature-Schwerpunkt.
  • SHAPE@XYZEin Tupel von XYZ-Koordinaten für den Feature-Schwerpunkt.
  • SHAPE@TRUECENTROIDEin Tupel von XY-Koordinaten für den Feature-Schwerpunkt. Dies gibt denselben Wert zurück wie SHAPE@XY.
  • SHAPE@XX-Koordinate des Features als Zahlenwert (Double).
  • SHAPE@YY-Koordinate des Features als Zahlenwert (Double).
  • SHAPE@ZZ-Koordinate des Features als Zahlenwert (Double).
  • SHAPE@MM-Wertes des Features als Zahlenwert (Double).
  • SHAPE@JSONDie Esri JSON-Zeichenfolge für die Geometrie.
  • SHAPE@WKBDas Well-known Binary (WKB)-Format für OGC-Geometrie. Es bietet eine übertragbare Darstellung eines Geometriewertes in Form eines zusammenhängenden Datenstroms.Werte werden als bytearray-Objekt zurückgegeben, können aber als bytearray- oder bytes-Objekt aktualisiert werden.
  • SHAPE@WKTDas Well-Known Text (WKT)-Format für OGC-Geometrie. Es bietet eine übertragbare Darstellung eines Geometriewertes in Form einer Textzeichenfolge.
  • SHAPE@Ein Geometrie-Objekt für das Feature.
  • SHAPE@AREAFläche des Features als Zahlenwert (Double).
  • SHAPE@LENGTHLänge des Features als Zahlenwert (Double).
  • CREATED@Ein datetime-Objekt für den Zeitpunkt der Erstellung des Features. Dieses Feld ist schreibgeschützt.
  • CREATOR@Eine Zeichenfolge für den Benutzernamen des Benutzers, der das Feature erstellt hat. Dieses Feld ist schreibgeschützt.
  • EDITED@Ein datetime-Objekt für den Zeitpunkt der letzten Bearbeitung des Features. Dieses Feld ist schreibgeschützt.
  • EDITOR@Eine Zeichenfolge für den Benutzernamen des Benutzers, der das Feature zuletzt bearbeitet hat. Dieses Feld ist schreibgeschützt.
  • GLOBALID@Eine Zeichenfolge für die UUID (Universally Unique Identifier) des Features. Dieses Feld ist schreibgeschützt.
  • OID@Der Wert des Objekt-ID-Feldes.
  • SUBTYPE@Der Subtype-Code als ganze Zahl.
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.

(Der Standardwert ist 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.

(Der Standardwert ist 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.

(Der Standardwert ist False)

Boolean
sql_clause

A 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.

Use DISTINCT in a prefix clause.


with arcpy.da.UpdateCursor(
        in_features, 
        ["OID@", "STREET_NAME"], 
        sql_clause=("DISTINCT STREET_NAME", None)
) as cur:

Use TOP in a prefix clause and ORDER BY in a postfix clause.


with arcpy.da.UpdateCursor(
        in_features, 
        ['OID@', "ELEVATION"], 
        sql_clause=("TOP 5", "ORDER BY ELEVATION DESC")
) as cur:

Use GROUP BY in a postfix clause.


with arcpy.da.UpdateCursor(
        in_features, 
        ['STREET_NAME'], 
        sql_clause=(None, "GROUP BY STREET_NAME")
) as cur:

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.

Hinweis:

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.

(Der Standardwert ist (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
explicit
[explicit,...]

If a field has a default value and the field is nullable, using a value of True will explicitly override the default value and insert null values into the record. When using a value of False, the default value will be inserted instead of null.

Apply the explicit rule to all fields:

with arcpy.da.UpdateCursor(table, [field1, field2, field3], explicit=True) as cursor:
    ...

The explicit rule can also be applied to individual fields using a list of Boolean values. The list of values must be the same length as the list of fields.

Apply the explicit rule to only the first two fields:

with arcpy.da.UpdateCursor(table, [field1, field2, field3], explicit=[True, True, False]) as cursor:
    ...

(Der Standardwert ist False)

Boolean
spatial_filter

A geometry object used to spatially filter features. When this argument is specified, the cursor will limit the features returned, based on specified geometry and the spatial_relationship value.

(Der Standardwert ist None)

Geometry
spatial_relationship

The spatial relationship between the input and the query geometry in the spatial_filter argument. This argument is only applicable when specifying the spatial_filter argument.

  • INTERSECTS Rows are only returned when the spatial_filter geometry intersects the input row's geometry.
  • ENVELOPE_INTERSECTS Rows are only returned when the spatial_filter geometry's envelope intersects the input row's geometry.
  • INDEX_INTERSECTS Rows are only returned when the spatial_filter geometry's envelope intersects the index entry for the input row's geometry. Because it uses the underlying index grid, rather than the envelope of the feature, it is faster and is commonly used for return features for display purposes.
  • TOUCHES Rows are only returned when the spatial_filter geometry touches the input row's geometry.
  • OVERLAPS Rows are only returned when the spatial_filter geometry overlaps the input row's geometry.
  • CROSSES Rows are only returned when the spatial_filter geometry crosses the input row's geometry.
  • WITHIN Rows are only returned when the spatial_filter geometry is within the input row's geometry.
  • CONTAINS Rows are only returned when the spatial_filter geometry contains the input row's geometry.

(Der Standardwert ist INTERSECTS)

String
search_order

The order in which the spatial searches are applied by the RDBMS. This property only affects enterprise geodatabase data and is only applicable when specifying the spatial_filter argument.

  • ATTRIBUTEFIRSTThe attribute query will be applied first.
  • SPATIALFIRST The spatial query will be applied first.

(Der Standardwert ist ATTRIBUTEFIRST)

String

Eigenschaften

EigenschaftErläuterungDatentyp
fields
(Schreibgeschützt)

A tuple of field names used by the cursor.

The tuple will include all fields and tokens specified by the field_names argument.

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

If the field_names argument is set to *, the fields property will include all fields used by the cursor. A value of * will return geometry in a tuple of x,y coordinates (equivalent to the SHAPE@XY token).

tuple

Methodenübersicht

MethodeErläuterung
deleteRow ()

Deletes the current row.

reset ()

Resets the cursor back to the first row.

updateRow (row)

Updates the current row in the table.

Methoden

deleteRow ()
reset ()
updateRow (row)
ParameterErläuterungDatentyp
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

Codebeispiel

UpdateCursor example 1

Use UpdateCursor to update a field value by evaluating the values of other fields.

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)
UpdateCursor example 2

Use UpdateCursor to update a field of buffer distances for use with the Buffer function.

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.analysis.Buffer(fc, 'roads_buffer', 'BUFFER_DISTANCE')
UpdateCursor example 3

Use UpdateCursor with a spatial filer to update field values.

import arcpy

arr = arcpy.Array(
    [arcpy.Point(342917.4, 553980.8), arcpy.Point(366915.9, 594749.1)]
)
new_road = arcpy.Polyline(arr, spatial_reference=arcpy.SpatialReference(26971))

fc = r"C:\data\chicago.gdb\houses"
fields = ["OCCUPIED"]

with arcpy.da.UpdateCursor(
    fc, fields, where_clause="OCCUPIED != 'Vacant'", spatial_filter=new_road
) as cursor:
    for row in cursor:
        row[0] = 'Vacant'
        cursor.updateRow(row)

Verwandte Themen