SearchCursor

サマリー

Establishes read-only access to the records of a feature class or table.

It returns an iterator of tuples. The order of values in the tuple matches the order of fields specified by the field_names argument.

Learn more about data access using cursors

説明

Geometry object properties can be accessed by specifying the token SHAPE@ in the list of fields.

Search cursors can be iterated using a for loop. Search 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.

The records returned by SearchCursor can be constrained to match attribute criteria or spatial criteria.

Accessing full geometry with SHAPE@ is an expensive operation. If only simple geometry information is required, such as the x,y coordinates of a point, use tokens such as SHAPE@XY, SHAPE@Z, and SHAPE@M for faster, more efficient access.

構文

SearchCursor (in_table, field_names, {where_clause}, {spatial_reference}, {explode_to_points}, {sql_clause}, {datum_transformation}, {spatial_filter}, {spatial_relationship}, {search_order})
パラメーター説明データ タイプ
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.

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

  • SHAPE@XYフィーチャの重心を表す X 座標と Y 座標の組み合わせ
  • SHAPE@XYZフィーチャの重心を表す XYZ 座標の組み合わせ
  • SHAPE@TRUECENTROIDフィーチャの重心を表す X 座標と Y 座標の組み合わせ SHAPE@XY と同じ値が返されます。
  • SHAPE@Xフィーチャの X 座標 (Double)
  • SHAPE@Yフィーチャの Y 座標 (Double)
  • SHAPE@Zフィーチャの Z 座標 (Double)
  • SHAPE@Mフィーチャの M 値 (Double)
  • SHAPE@JSONジオメトリを表す Esri JSON 文字列
  • SHAPE@WKBOGC ジオメトリの WKB (Well-Known Binary) 表現。 ジオメトリ値の汎用的な表現が、連続的なバイト ストリームとして提供されます。値は bytearray オブジェクトとして返されます。
  • SHAPE@WKTOGC ジオメトリの WKT (Well-Known Text) 表現。 ジオメトリ値の汎用的な表現が、テキスト文字列として提供されます。
  • SHAPE@フィーチャのジオメトリ オブジェクト
  • SHAPE@AREAフィーチャの面積 (Double)
  • SHAPE@LENGTHフィーチャの長さ (Double)
  • CREATED@フィーチャが作成されたときの datetime オブジェクト。 このフィールドは読み取り専用です。
  • CREATOR@フィーチャを作成したユーザー名の文字列。 このフィールドは読み取り専用です。
  • EDITED@フィーチャが最後に編集されたときの datetime オブジェクト。 このフィールドは読み取り専用です。
  • EDITOR@フィーチャを最後に編集したユーザー名の文字列。 このフィールドは読み取り専用です。
  • GLOBALID@フィーチャのユニバーサルに一意な識別子の文字列。 このフィールドは読み取り専用です。
  • OID@Object ID フィールドの値
  • SUBTYPE@サブタイプ コードの整数。
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.

(デフォルト値は次のとおりです 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.

(デフォルト値は次のとおりです 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.

(デフォルト値は次のとおりです 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.SearchCursor(
        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.SearchCursor(
        in_features, 
        ['OID@', "ELEVATION"], 
        sql_clause=("TOP 5", "ORDER BY ELEVATION DESC")
) as cur:

Use GROUP BY in a postfix clause.


with arcpy.da.SearchCursor(
        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.

注意:

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.

(デフォルト値は次のとおりです (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

(デフォルト値は次のとおりです None)

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

(デフォルト値は次のとおりです 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.

(デフォルト値は次のとおりです 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.

(デフォルト値は次のとおりです ATTRIBUTEFIRST)

String

プロパティ

プロパティ説明データ タイプ
fields
(読み取り専用)

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

方法の概要

方法説明
reset ()

Resets the cursor back to the first row.

方法

reset ()

コードのサンプル

SearchCursor example 1

Use SearchCursor to step through a feature class and print specific field values and the x,y coordinates of the point.

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]))
SearchCursor example 2

Use SearchCursor to return a set of unique field values.

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)
SearchCursor example 3

Use SearchCursor to return attributes using 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]))
SearchCursor example 4

Use SearchCursor with a where clause to identify features that meet specific criteria.

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])
SearchCursor example 5

Use SearchCursor and the Python sorted method to sort rows.

For additional sorting options, see the Python Sorting Mini-HOW TO.

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(f'{row[0]}, {row[1]}')
SearchCursor example 6

Alternatively, sort using sql_clause if the data supports the SQL ORDER BY clause.

注意:

The ORDER BY clause is only supported when working with databases. It is not supported by other data sources (such as dBASE).

import arcpy

fc = 'c:/data/base.gdb/well'
fields = ['WELL_ID', 'WELL_TYPE']

# Use ORDER BY sql clause to sort field values
with arcpy.da.SearchCursor(fc, fields, sql_clause=(None, "ORDER BY WELL_ID, WELL_TYPE")) as cursor:
    for row in cursor:
        print(f'{row[0]}, {row[1]}')
SearchCursor example 7

Use the SQL TOP clause to limit the number of records to return.

注意:

The TOP clause is only supported by SQL Server databases.

import arcpy

fc = 'c:/data/base.mdb/well'
fields = ['WELL_ID', 'WELL_TYPE']

# Use SQL TOP to sort field values
with arcpy.da.SearchCursor(fc, fields, sql_clause=('TOP 3', None)):
    for row in cursor:
        print(f'{row[0]}, {row[1]}')
SearchCursor example 8

Use SearchCursor using a spatial filter with a geometry object.

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 = ["ADDRESS", "OCCUPIED"]

with arcpy.da.SearchCursor(
    fc, fields, where_clause="OCCUPIED != 'Vacant'", spatial_filter=new_road
) as cursor:
    for row in cursor:
        print(f'{row[0]}: {row[1]}')
SearchCursor example 9

Use SearchCursor using a spatial filter with a geometry object from another feature class.

import arcpy

fc = r"c:\connections\sqlserver.sde\DBO.ShipPositions"
fields = ["OBJECTID", "SHIP_NAME"]
searchPoly = [row[0] for row in arcpy.da.SearchCursor("searchArea", ["SHAPE@"])][0]

with arcpy.da.SearchCursor(
    fc, fields, spatial_filter=searchPoly, search_order="SPATIALFIRST"
) as cursor:
    for row in cursor:
        print(f'{row[0]}: {row[1]}')

関連トピック