I'm trying to update a column based on the value in the next row, but cursor.next()
is giving unexpected behavior. When I identify the next_row using cursor.next()
, it is resetting my row in cursor
! The result is my loop goes over every other row, not every row. What am I missing? (Code below is just to show cursor behavior; code for row update for column has been stripped.)
Code
import arcpy
temp1 = r'mypath\mypointfile.shp'
with arcpy.da.UpdateCursor(temp1, ['OID@']) as cursor:
for row in cursor:
try:
row_next = cursor.next()
print 'current_oid=', row[0], 'next_oid=', row_next[0]
except StopIteration:
print 'no rows'
except:
print 'something else went wrong'
Actual Prints
current_oid= 0 next_oid= 1
current_oid= 2 next_oid= 3
current_oid= 4 next_oid= 5
current_oid= 6 next_oid= 7
current_oid= 8 next_oid= 9
Expected Prints
current_oid= 0 next_oid= 1
current_oid= 1 next_oid= 2
current_oid= 2 next_oid= 3
current_oid= 3 next_oid= 4
current_oid= 4 next_oid= 5
UPDATE
Purpose of this is to only keep rows that are the first or last point in the group.
Example attributes:
oid group id
0 1 1
1 1 2
2 1 3
3 2 1
4 2 2
5 3 1
6 3 2
7 3 3
8 3 4
9 3 5
Desired attributes:
group id
1 1
1 3
2 1
2 2
3 1
3 5
Original code, that didn't work because cursor.next() skips rows:
with arcpy.da.UpdateCursor(temp1, ['OID@', 'group', 'id']) as cursor:
for row in cursor:
group_current = row[1]
id_current = row[2]
if id_current == 1:
check = "keep"
else:
try:
row_next = cursor.next()
group_next = row_next[1]
id_next = row_next[2]
if id_next == 1:
check = "keep"
else:
check = "remove"
except StopIteration:
check = "keep"
except:
print 'something else went wrong'
if check != "keep":
cursor.deleteRow()
next
isn't needed, because you're in afor
loop. You can't read ahead, but you can preserve the current inprevious
then act on that later.