2

I'm new to ArcPy and have a question about ArcPy search cursors. I need to compare the current row of a point shapefile to the previous row for string field "Cat" and IF they are equal then I want to print the FID, ELSE print "NoMatch".

Code and data found below. The issue is cursor.next() seems to skip a row perhaps? The output is 1, 3, 5, 7, 9 when it should be 1, 2, 3, 5, 6, 8, 9, 10 (note 4 and 7 should not print because the "Cat" field value does match the previous). Also not sure why 7 was returned in the result.

DATA

FID Cat POINT_X POINT_Y
0 Sand 619557.6 4843930.0 
1 Sand 619515.4 4843900.5
2 Sand 619513.8 4843899.7
3 Sand 619512.6 4843898.6
4 Gravel 619511.3 4843897.5
5 Gravel 619508.8 4843895.5
6 Gravel 619507.5 4843894.5
7 Sand 619495.5 4843883.5
8 Sand 619486.1 4843876.3
9 Sand 619484.1 4843875.3
10 Sand 619476.0 4843870.2

CODE

import arcpy 
shp = "C:\TEST.shp" 
cursor = arcpy.SearchCursor(shp)
for row in cursor:
    rowCur = row
    rowPost = cursor.next()

    if rowPost.getValue("Cat")==rowCur.getValue("Cat"):
        print (row.getValue("FID"))
    else:
        print "NoMatch"
  • 1
    What version of ArcGIS? – Midavalo Aug 29 '16 at 19:19
  • I don't think you are using next correctly. It isn't a reference to the next value, it is a method (an action) moving you to the next row. – jbchurchill Aug 29 '16 at 19:22
  • You do not need to use the next() if you are using a for loop – ziggy Aug 29 '16 at 19:23
  • Not telling us the version of ArcGIS you are using is preventing potential answerers from giving what I suspect will be the most useful answer to you. – PolyGeo Aug 29 '16 at 20:48
  • The most important advice I can give on Cursor use is: Don't use them. 10.1 introduced Data Access Cursors (DA cursors). Which are much faster and more Pythonic than the old Cursors. Given that 10.0 and earlier are now retired, it's also time to retire Cursor use. – Vince Aug 29 '16 at 22:14
1

Try something along these lines (warning: this is untested).

import arcpy 
shp = "C:/TEST.shp" 
cursor = arcpy.SearchCursor(shp)
previousValue = ""
for row in cursor:
    rowCur = row
    # rowPost = cursor.next()

    if row.getValue("Cat")== previousValue:
        print (row.getValue("FID"))
    else:
        print "NoMatch"
    previousValue = row.getValue("Cat")
  • 1
    This solution has worked. Setting up the previousValue variable before entering the for loop was what I was missing. Rookie programming mistake, but I'm learning. Thanks, much appreciated! – Andrew15 Aug 30 '16 at 11:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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