I am trying to write a script that iterates through each row of a table, calculates for this row something. The result of this calculation is finally stored in another table (with just one row). Now I want to add this value to the starting table in the same row. And that is where I am stuck. I tried to work with SearchCursor and UpdateCursor but I am not sure how to make it work between these two tables. (Join is not possible, as there is no field the join could be based on)
Sorry, here is the script. The problem is really at the end.
import arcpy
from arcpy import env
from arcpy.sa import *
# Set the workspace
env.workspace = "D:/next/"
env.scratchWorkspace = "D:/next/"
# Set object property to overwrite existing output
arcpy.gp.overwriteOutput = True
# Check out the ArcGIS Spatial Analyst extension license arcpy.CheckOutExtension("Spatial")
# Set Raster Variable
inRaster = arcpy.GetParameterAsText(0)
FieldName = arcpy.GetParameterAsText(1)
inputFeature = arcpy.GetParameterAsText(2)
#Add a field to the inputFeature, for results
arcpy.AddField_management(inputFeature, FieldName, "LONG")
#Create the search cursor
rows = arcpy.SearchCursor(inputFeature)
for row in rows:
# Create a Where Clause to select only the current record
whereClause = '"FID" = ' + str(row.FID)
IDField = str(row.FID)
tempData = "row" + IDField + ".shp"
# Create a feature layer from the current row only
arcpy.MakeFeatureLayer_management(inputFeature, tempData, whereClause)
# Extract the cells of a raster that underly the selected feature
maskedRaster = ExtractByMask(inRaster, tempData)
maskedRaster.save ("D:/next/" + "row" + str(IDField))
# Create the table for the new "maskedRaster" (for each value a row and the count of the values)
newRaster = "row" + str(IDField)
arcpy.BuildRasterAttributeTable_management(newRaster, "NONE")
# here would be all the calculations
# I leave them out the skript is long enough, already
# Summarize the values. A dbf-table with only one row is the result
stat = [["Calc", "SUM"]]
arcpy.Statistics_analysis(newRaster, str(newRaster)+".dbf", stat )
# Now create an update Cursor to add the value to the selected row
rows2 = arcpy.UpdateCursor(inputFeature)
# Here comes the problem
for row2 in rows2:
if row2.FID == IDField:
row2.setValue(FieldName, row2.getValue(arcpy.CalculateField_management(str(newRaster)+".dbf", "SUM_Calc"))
rows2.updateRow(row2)
del row2, rows2
del row, rows
Best Answer
It looks like you are attempting two cursors on the same feature class at the same time. I am fairly certain that will not work.
From Accessing data using cursors, 10.0:
If you have all your calculations stored by FID, finish the first cursor in the first loop and then start the second as a separate loop.