Monday, June 18, 2012

10.1 SearchCursor (arcpy.da)

The Search Cursor object creates read-only access to the records in a feature class or table.  It will return an iterator of tuples.  The order of values matches the order of fields mentioned by the field_names argument.

When comparing the old search cursor to the new search cursor, functionally they are basically the same, except the data access module is better, stronger, and faster. It's like the Six Million Dollar Man of upgrades in ArcPy.

Looking at the inputs:
SearchCursor (in_table, field_names, {where_clause}, {spatial_reference}, {explode_to_points}, {sql_clause})


The two biggest differences between arcpy.SearchCursor and arcpy.da.SearchCursor, is the field_names is required, and the optional parameter explode_to_points.


Paramter field_names can be "*", which means all fields, but it does exclude BLOB and raster fields.  This is required because you should only be returning what you need.  The other interesting aspect of the is the way you can obtain geometry and other field information using the @.

  • SHAPE@XY —A tuple of the feature's centroid x,y coordinates
  • SHAPE@TRUECENTROID —A tuple of the feature's true centroid x,y coordinates
  • SHAPE@X —A double of the feature's x-coordinate
  • SHAPE@Y —A double of the feature's y-coordinate
  • SHAPE@Z —A double of the feature's z-coordinate
  • SHAPE@M —A double of the feature's m-value
  • SHAPE@ —A geometry object for the feature
  • SHAPE@AREA —A double of the feature's area
  • SHAPE@LENGTH —A double of the feature's length
  • OID@ —The value of the ObjectID field

The parameter explode_to_points is a boolean value.  If you specify the value to true, it will explode multi-geometry values into there own rows.  This means if you have a 5 multipoint geometry object, it will have 5 rows instead of 1.

Example: Basic Use
import arcpy
fc = r"c:\temp\wells.shp"
fields = ["WELL_ID","TYPE","SHAPE@XY"]
with arcpy.da.SearchCursor(fc,fields) as cursor:
   for row in cursor:
      print "{0}, {1}, {2}".format(row[0],row[1],row[2])

So here we have just a simple read-only example where the user will pass in a feature class and the fields needed to query.  It will print the information out on the screen.  Notice the usage of the with statement.  This is great because it automatically cleans up the cursor object.  This means no more del statements and help reduce the number of cursor locks on data.

Enjoy

1 comment:

redtrails said...

Good post. I recently wanted to make use of the explode_to_points and learned that you _must_ include the SHAPE@Y and SHAPE@X fields in the field_names array or it won't work. Keep up the good work.