2

I am matching data using a cursor, where one of the final steps is filling in a new attribute, match, with a value calculated during the cursor. This matching is done to an ID field in the original data that is often shared by many points (i.e. there are 200 points with VID 8, and they will all end up with the same match value, 284). I am looking for a way to speed up my script by setting the match value on all common VIDs so instead of running the cursor on every point data, it is only run on the unique VIDs (unfortunately other steps in my script make dissolving this data into multi-point impossible). If this were not done inside a Cursor, I would select by VID attribute and then use the calculate field tool. Is there a way to batch set values or get around the schema lock issue for the calculate field tool inside a cursor?
Here is a sample of the code (simplified) if I could use Calculate Field:

rows = arcpy.SearchCursor("logbook") #Temporarily a SearchCursor, but I've tried with UpdateCursor as well.
for row in rows:
    if row.match > 0: #If the VID has already been matched, this will skip the calculations for it
        continue
    else:
        #(My matching and value calculating processes)#
        arcpy.SelectLayerByAttribute_management("logbook", "NEW_SELECTION", ' "VID" = ' + str(row.VID))
        arcpy.CalculateField_management("logbook", "match", int(match_val))
del row, rows

Any thoughts? Or am I doomed to have a script that takes much longer than necessary?

3
  • Perhaps think about using a Python dictionary - there's a good example here
    – PolyGeo
    Commented Feb 21, 2013 at 1:17
  • You mentioned you tried using an UpdateCursor. What went wrong there? Post the code you used.
    – blah238
    Commented Feb 21, 2013 at 17:42
  • See also this answer to a related question: How can I more efficiently select related records?
    – blah238
    Commented Feb 21, 2013 at 17:45

2 Answers 2

2

Perhaps try using the arcpy.UpdateCursor method to calculate the new values. See the older article HowTo: Use Python UpdateCursor method to calculate values in a table based on another field and modify to use with arcpy (instead of arcgisscripting).

You could also try the data access module in arcpy for Specifying a query in Python. The code sample example 1 for arcpy.da.UpdateCursor appears to do what you need.

1
0

If you don't need to do this in a cursor, a different approach is to perform the 'selection' inside the Calculate Field tool's code block - see the specific example for 'Calculate fields using logic with Python'. Depending on the number of records to be processed, and the number of if statements, this may or may not be any faster than inside a cursor.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.