I am trying to write some python code to calculate a change in Z value from one point to the next. I have a number of point files with Z values in a field called "RASTERVALU". I have a field called zdiff that I would like to update with " Zdiff(row1)=Z(row2)-Z(row1)". I can use the update cursor it to look at the backwards change (Zdiff(row1)=z(row1)-Z(row0)) but not the forward change (Zdiff(row1)=z(row1)-Z(row0)).
I used the following code below but it seems like the updaterow.next() is messing up my sequential flow through the rows. Let me know if anyone has any ideas:
updateRows=arcpy.da.UpdateCursor(OutputFileName,["RASTERVALU","zDiff"])
for row in updateRows:
nextRow=updateRows.next()
zdiff=nextRow[0]-row[0]
row[1]=zdiff
updateRows.updateRow(row)
The first run through the loop works ok but then it iterates to the third row instead of the second row. I assume it is because of my use of updateRows.next() but I am not sure. I can’t find very good documentation of the updateRow.next or any of the cursor information.
Any thoughts?
Ian
Solved! Go to Solution.
Try the following:
valueList = [] with arcpy.da.SearchCursor(OutputFileName, ["RASTERVALU"]) as cursor: for row in cursor: valueList.append(row[0]) del cursor x = 1 with arcpy.da.UpdateCursor(OutputFileName, ["RASTERVALU", "zDiff"]) as cursor: for row in cursor: try: value = valueListexcept: value = valueList[-1] row[1] = row[0] - value x += 1 cursor.updateRow(row) del cursor
Hi Ian,
Here is one way you can do this:
with arcpy.da.UpdateCursor(OutputFileName, ["RASTERVALU", "zDiff"]) as cursor:
firstTime = True
for row in cursor:
if firstTime:
diff = row[0]
row[1] = 0
firstTime = False
else:
row[1] = row[0] - diff
diff = row[0]
cursor.updateRow(row)
del cursor
Hi Jake, Thanks for your help. I may be mistaken but I think your code gets me the backward calc. I need the forward calc. I put your code in and ran it and it gave me the below output. I need the -1.442169 in the first row, not the second row. This is because it is associated with other attributes in that row.
Thanks again for your help,
Ian
Try the following:
valueList = [] with arcpy.da.SearchCursor(OutputFileName, ["RASTERVALU"]) as cursor: for row in cursor: valueList.append(row[0]) del cursor x = 1 with arcpy.da.UpdateCursor(OutputFileName, ["RASTERVALU", "zDiff"]) as cursor: for row in cursor: try: value = valueListexcept: value = valueList[-1] row[1] = row[0] - value x += 1 cursor.updateRow(row) del cursor
Jake, Thanks so much. That worked and it was really helpful. The code with the searchCursor will also help me many other places in my work.
Thanks again,
Ian