I am trying to compare two values, and can't seem to access the next row in a cursor.
for i, row in enumerate(cursor):
if row[0] == cursor.next()[0]
Any ideas?
Solved! Go to Solution.
See this thread for ideas: Compare value from n and n+1 row in searchCursor
See this thread for ideas: Compare value from n and n+1 row in searchCursor
Beyond reading through the thread recommended by Randy Burton, a couple of questions:
UPDATE: continued....
As mentioned in the referenced GeoNet discussion, ArcPy cursors do not implement any kind of look- or read-ahead feature. If one is working solely within DBMSs, there are likely set-based approaches that are better then using cursors for look-ahead functionality, .e.,g LAG and LEAD functionality implemented in many DBMSs; but one needs to work with what is available to them.
There are multiple ways to emulate look- or read-ahead functionality with Python and ArcPy, several are covered in the aforementioned GeoNet discussion. Since I commented on that discussion last year, I have refined the approach I put forward. Functionally, the approach below is not any different, but syntactically it is much more streamlined, I would argue more Pythonic.
from itertools import izip_longest
fc = # path to feature class
flds = # string list of field names for cursors
with arcpy.da.SearchCursor(fc, flds) as n1_cur:
with arcpy.da.UpdateCursor(fc, flds) as n_cur:
filler_row = next(n1_cur)
for n_row, n1_row in izip_longest(n_cur, n1_cur, fillvalue=filler_row):
if n_row[0] == n1_row[0]:
n_cur.updateRow([...])
The basic approach is to pair a search cursor with an update cursor. The search cursor is used for the look ahead (n+1 cursor or n1_cur) while the update cursor is used for the current record (n cursor or n_cur). The itertools.izip_longest() function is used to pair the two cursors so they can be stepped through together, with the search cursor being one record ahead of the update cursor.
UPDATE 2: Removed empty_row and created filler_row since previous code for empty_row would fail with datetime or geometry fields.