Thursday, 17 December 2015

arcgis desktop - How to access adjacent rows with cursor?


In the attached screenshot, the attributes contain two field of interest "a" and "b". I want to write a script to access the adjacent rows in order to make some calculations. To access a single row, I would use the following UpdateCursor:


fc = r'C:\path\to\fc'

with arcpy.da.UpdateCursor(fc, ["a", "b"]) as cursor:
for row in cursor:
# Do something


For example, with OBJECTID 4, I am interested in calculating the sum of the row values in field "a" adjacent to OBJECTID 4 row (i.e. 1 + 3) and adding that value to the OBJECTID 4 row in the "b" field. How can I access adjacent rows with the cursor to make these sort of calculations?


enter image description here



Answer



If this was me I would pass through the table once creating a dictionary where key is OBJECTID and item is the value in field "a". I would then then step through the table with an update cursor getting the OBJECTID and from that I could get the adjacent values from the dictionary, sum them and write them back to field "b".


But in your screenshot you have special cases for rows 3 and 8 as they only have one adjacent row. What would you intend for these?


No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...