Sunday, 1 January 2017

Using Update Cursor in a double for loop in arcpy



I have some problems using a double for loop and getting results written into a geodatabase.


I have got a shapefile with polygons (param_polygone) and I want to add data to it, which is stored in a table (table_datei). In the polygon shapefile I have got features with an unique ID, called "FID". In the table I have got fields, which store lenghts ("LENGTH") belonging to a polygon (src_FID). So often I there are several lengths stored for one polygon. For example there is one FID in the polygon shapefile, which is 0 and several entries or rows in the table, where the src_FID is 0 and where unique lengths are stored in the same row. I want to sum up all lengths of one src_FID and store it in the field "Nbr_Laenge", which belongs to the FID that is the same value as the src_FID.


Somehow only the first value gets sumed up in "Nbr_Laenge". All the others have the value 0 in the end of the execution.


Here is what I got so far:


table_cursor = arcpy.da.UpdateCursor(table_datei, ["src_FID", "LENGTH"])
geb_cursor = arcpy.da.UpdateCursor(param_polygone, ["FID", "Nbr_Laenge"])
for geb_row in geb_cursor:
for table_row in table_cursor:
if table_row[0] == geb_row[0]:
geb_row[1]=geb_row[1]+table_row[1]

geb_cursor.updateRow(geb_row)

Something with the for-loops isn't working properly. I am new to python and working with ArcGIS.



Answer



You don't need a nested loop (and it's written in a wrong way because you will scan your table only once)


So. First of all read all the data from the table and sum it up.


data = {}
with arcpy.da.SearchCursor(table_datei, ["src_FID", "LENGTH"]) as sc:
for row in sc:
try:

data[row[0]] = data[row[0]] + row[1]
except KeyError:
data[row[0]] = row[1]

This will give you a dictionary {data} with keys as your FID and values as a sum of all lenghts linked to this FID.


Next, start an update cursor and write it to your FC:


with arcpy.da.UpdateCursor(param_polygone, ["FID", "Nbr_Laenge"]) as uc:
for row in uc:
row[1] = data[row[0]]
uc.updateRow(row)


That's it.


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...