Resumen
SearchCursor establece acceso de solo lectura a los registros devueltos de una tabla o clase de entidad.
Devuelve un iterador de tuplas. El orden de los valores en la tupla coincide con el orden de los campos especificados por el argumento field_names.
Debate
Geometry es posible acceder a las propiedades especificando el token SHAPE@ en la lista de campos.
Es posible iterar los cursores de búsqueda mediante un bucle for. Los cursores de búsqueda 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.
Los registros que devuelve SearchCursor se pueden restringir para que coincidan con los criterios de atributos o espaciales.
Acceder a la geometría completa con SHAPE@ es una operación costosa. Si solo se requiere información de geometría sencilla, como las coordenadas x,y de un punto, utilice tokens como SHAPE@XY, SHAPE@Z y SHAPE@M para un acceso más rápido y eficiente.
En Python 2, SearchCursor admite el método next de iterador para recuperar la siguiente fila fuera de un bucle. En Python 3, se realiza lo equivalente mediante la función next integrada de Python.
Sintaxis
SearchCursor (in_table, field_names, {where_clause}, {spatial_reference}, {explode_to_points}, {sql_clause}, {datum_transformation})
Parámetro | Explicación | Tipo 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:
| 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. If a spatial reference is specified, but the input feature class has an unknown spatial reference, neither a projection nor transformation can be completed. The geometry returned by the cursor will have coordinates matching the input, with a spatial reference updated to the one specified. (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. The ListTransformations function can be used to provide a list of valid datum transformations between two spatial references. Learn more about datum transformations (El valor predeterminado es None) | String |
Propiedades
Propiedad | Explicación | Tipo 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étodo | Explicación |
reset () | Resets the cursor back to the first row. |
Métodos
reset ()
Muestra de código
Use SearchCursor para recorrer una clase de entidad e imprimir valores de campo específicos y las coordenadas x,y del punto.
import arcpy
fc = 'c:/data/base.gdb/well'
fields = ['WELL_ID', 'WELL_TYPE', 'SHAPE@XY']
# For each row, print the WELL_ID and WELL_TYPE fields, and
# the feature's x,y coordinates
with arcpy.da.SearchCursor(fc, fields) as cursor:
for row in cursor:
print(u'{0}, {1}, {2}'.format(row[0], row[1], row[2]))
Use SearchCursor para devolver un conjunto de valores de campo únicos.
import arcpy
fc = 'c:/data/base.gdb/well'
field = 'Diameter'
# Use SearchCursor with list comprehension to return a
# unique set of values in the specified field
values = [row[0] for row in arcpy.da.SearchCursor(fc, field)]
uniqueValues = set(values)
print(uniqueValues)
Use SearchCursor para devolver atributos con tokens.
import arcpy
fc = 'c:/data/base.gdb/well'
# For each row, print the Object ID field, and use the SHAPE@AREA
# token to access geometry properties
with arcpy.da.SearchCursor(fc, ['OID@', 'SHAPE@AREA']) as cursor:
for row in cursor:
print('Feature {} has an area of {}'.format(row[0], row[1]))
Use SearchCursor con una cláusula WHERE para identificar entidades que cumplen criterios concretos.
import arcpy
fc = 'c:/base/data.gdb/roads'
class_field = 'Road Class'
name_field = 'Name'
# Create an expression with proper delimiters
expression = u'{} = 2'.format(arcpy.AddFieldDelimiters(fc, name_field))
# Create a search cursor using an SQL expression
with arcpy.da.SearchCursor(fc, [class_field, name_field],
where_clause=expression) as cursor:
for row in cursor:
# Print the name of the residential road
print(row[1])
Use SearchCursor y el método de ordenación de Python para ordenar filas.
Para ver más opciones de ordenación, consulte el Miniprocedimiento de ordenación de Python.
import arcpy
fc = 'c:/data/base.gdb/well'
fields = ['WELL_ID', 'WELL_TYPE']
# Use Python's sorted method to sort rows
for row in sorted(arcpy.da.SearchCursor(fc, fields)):
print(u'{0}, {1}'.format(row[0], row[1]))
Como alternativa, ordene con sql_clause si los datos admiten ORDER BY de SQL.
Nota:
ORDER BY solo se admite al trabajar con bases de datos. Ninguna otra fuente de datos lo admite (como las tablas INFO o dBASE).
import arcpy
fc = 'c:/data/base.gdb/well'
fields = ['WELL_ID', 'WELL_TYPE']
# Use ORDER BY sql clause to sort field values
for row in arcpy.da.SearchCursor(
fc, fields, sql_clause=(None, 'ORDER BY WELL_ID, WELL_TYPE')):
print(u'{0}, {1}'.format(row[0], row[1]))
Use TOP de SQL para limitar el número de registros que se devuelven.
Nota:
TOP solo se admite en bases de datos de SQL Server y MS Access.
import arcpy
fc = 'c:/data/base.mdb/well'
fields = ['WELL_ID', 'WELL_TYPE']
# Use SQL TOP to sort field values
for row in arcpy.da.SearchCursor(fc, fields, sql_clause=('TOP 3', None)):
print(u'{0}, {1}'.format(row[0], row[1]))