Can anyone tell me if there is a way to go up one row in python cursor?
i.e. opposite of row = rows.next()
Geographic Information Systems Stack Exchange is a question and answer site for cartographers, geographers and GIS professionals. It only takes a minute to sign up.Sign up to join this community
Most cursors don't support iterating backward, but there's an easy way to get the previous row's value, just store a variable:
previous_row = None for row in rows.next(): # do stuff here ... # now, store the value of the current row into previous row before # the next iteration is started previous_row = row
If you have a need to reset the cursor, many support a reset operation. If you're using ArcGIS, this is
Update: Arash asked how to get values that are even earlier in the dataset. One way would be to store multiple previous rows, extending the logic above. If the dataset is small, another approach would be to store the values already seen in a list of tuples, and index the cursor. The code above does this based on the specific question asked:
previous_data =  for (i, row) in enumerate(rows.next()): x = row y = row # add this record to our 'seen' data: previous_data.append((x, y)) # now, if we need a previous point, we can ask for it by index if i >= 2: (n, m) = previous_data[i-2] # now n and m store the values seen two records previously.
What about putting row in the list and iterating backwards?
EDIT: Turns out, that rows object does not work this way :) and row in the list lost reference. But depending on your needs, you may put on the list row.whatever_you_may_need and then iterate backwards. Of course this may work only for SearchCursor and only for some use cases. Also you may check how the rows.next() is iterating over the rows container, if it depends on fetures FID or something else, you may try to revers feature order in FC (also may be option for some caseses).