[GIS] arcpy: check for same record in cell above and below

arcgis-10.0arcpyfield-calculatorpython

After using the find duplicates in arcmap 10, I want to check if the feat sequence ("find duplicates" marks all records with the same attributes with the same number [in "feat_seq"] and creates a ROWID_ that has unique numbers for each record) is the same in the cell above and below and record and if it is the same then mark the duplicate/triplicate etc as "1", if not mark with 0.

The logic we used in excel is
=IF(OR(C1=C2,C3=C2),1,0)

If c2 = c1 or c2 =c3, give the cell a value of 1, if not, give the
cell a value of 0. Used to identify duplicate values that are in
order. If the cell above or below is the same as the cell in
question, give the cell a value of 1. If not, give the cell a value
of 0.

The code I started to write was

import arcpy
rows = arcpy.UpdateCursor("TestDuplicateID")

for row in rows:
    rowCur=row
    rowPost= row.next()
    rowPre= # how can we get this?


    if rowCur.getValue("FEAT_SEQ")==row.getValue("FEAT_SEQ"):
        rowCur.setValue("Dups", "1")
    elif rowCur.getValue("FEAT_SEQ")==rowPre.getValue("FEAT_SEQ"):
        rowCur.setValue("Dups", "1")
    else:
        rowCur.setValue("Dups","0")

I can't seem to find a way to retain the PRE record and get the following error "Runtime error : unsupported operand type(s) for -: 'Row' and 'int'".

Thanks for your help

Best Answer

Cursors can be tricky, since they only look at one row at a time, and don't like to bounce around arbitrarily. I would sweep through your table twice: once with a SearchCursor, and second with an UpdateCursor.

import arcpy
rows = arcpy.SearchCursor("TestDuplicateID")

# Get first two values
v0 = rows.next().FEAT_SEQ
v1 = rows.next().FEAT_SEQ
# First comparison
unique = [v0 == v1]
# Compare middle rows
for row in rows:
    v2 = row.FEAT_SEQ
    # Middle comparisons
    unique.append(v0 == v1 or v1 == v2)
    # Shift values for next loop
    v0, v1 = v1, v2
# Last comparison
unique.append(v0 == v1)

# Copy the results back to table
rows = arcpy.UpdateCursor("TestDuplicateID")
for i, row in enumerate(rows):
    row.Dups = int(unique[i])
    rows.updateRow(row) 
Related Question