TransWikia.com

Python scripting (update cursor, extract previous row values)

Geographic Information Systems Asked by zitJack on December 12, 2020

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 

One Answer

A little bit convoluted but it works:

import arcpy

tbl = r'C:GISdata.gdbtbl'
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:GISdata.gdbtbl_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)

Answered by BERA on December 12, 2020

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP