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"
-
1What version of ArcGIS?Midavalo– Midavalo ♦2016年08月29日 19:19:30 +00:00Commented Aug 29, 2016 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– jbchurchill2016年08月29日 19:22:56 +00:00Commented Aug 29, 2016 at 19:22
-
You do not need to use the next() if you are using a for loopziggy– ziggy2016年08月29日 19:23:38 +00:00Commented Aug 29, 2016 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– PolyGeo ♦2016年08月29日 20:48:14 +00:00Commented Aug 29, 2016 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– Vince2016年08月29日 22:14:40 +00:00Commented Aug 29, 2016 at 22:14
1 Answer 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")
-
1This 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– Andrew152016年08月30日 11:19:29 +00:00Commented Aug 30, 2016 at 11:19