1

I am new to Python scripting.

I would like to use SearchCursor to iterate in each row using the FID as index. Then I would like to evaluate length based on the following conditions:

Table I am using

  • If the length >100 then (CAT remains at 0) and proceed to next row.
  • If the next length is less than 100, then it should go back to the previous (immediate) row (that has a value of >100) and extract values in that row (FID, Length, CAT), and save them in an empty table, then the script should stop there.

fields = ["FID", "Length","CAT"]

with arcpy.da.SearchCursor(fc, fields) as cursor:

    for row in cursor:
        if row[1] > 100:    
           print (row[2])        
    
        elif row[1] < 100:
           #Some code accessing the previous row here
           print (row[0], row[1], row[2]) #to test what is to be printed 
1
  • 1
    Just to be crystal clear using your example data screen shot the logic you state would end up with an output table that would have 4 new rows all with 6,114.612686,0? Is that what you intended. Its good practise when ask such questions to show what you actually want.
    – Hornbydd
    Commented Dec 10, 2020 at 22:52

1 Answer 1

1

A little bit convoluted but it works:

import arcpy

tbl = r'C:\GIS\data.gdb\tbl'
data = [row for row in arcpy.da.SearchCursor(tbl, ['OID@','length','CAT'])] #List all rows
#>>data
#[(1, 180, 0), (2, 179, 0), (3, 168, 0), (4, 141, 0), (5, 129, 0), (6, 125, 0), (7, 115, 0), (8, 70, 0), (9, 51, 0), (10, 16, 0), (11, 3, 0)]

for row1, row2 in zip(data, data[1:]): #For each pair of rows
    #print(row1, row2)
    #(1, 180, 0) (2, 179, 0)
    #(2, 179, 0) (3, 168, 0)    
    #...
    if row1[1]>100 and row2[1]<100:
        the_one = row1[0] #If true then store objectid as the_one variable
        break #No need to keep iterating after it is found
#>>the_one
#7 #My objectids start with 1

tbl_out = r'C:\GIS\data.gdb\tbl_out'
oidfield = arcpy.Describe(tbl).OIDFieldName
sql = "{0} = {1}".format(arcpy.AddFieldDelimiters(tbl, oidfield), the_one)
arcpy.MakeTableView_management(in_table=tbl, out_view='result', where_clause=sql)
arcpy.CopyRows_management(in_rows='result', out_table=tbl_out)
2
  • 1
    Thank you!!!! :)
    – zitJack
    Commented Dec 11, 2020 at 13:50
  • Nice, did it work? Then please accept my answer with the green checkbox
    – Bera
    Commented Dec 12, 2020 at 14:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.