Sunday, 9 February 2020

arcpy - Python conditional on current and previous row?


I need to calculate a new field with a python conditional where some values only occur if a sequence in a separate attribute field (X) occurs.

For instance my data set looks like this. Y is the attribute I want to fill out:


ID   X  Y
1 1 -
2 1 -
3 0 -
4 0 -
5 0 -
6 1 -
7 1 -
8 1 -

9 0 -
10 0 -
11 1 -

Values for Y:
If X = 1, Y = 1
If X = 0 and previous X = 1, Y = 2
If X = 0 and previous x = 0, Y = 0


So my data would look like:


ID   X  Y

1 1 1
2 1 1
3 0 2
4 0 0
5 0 0
6 1 1
7 1 1
8 1 1
9 0 2
10 0 0

11 1 1

I have seen previous lines stored using:


prev_X = ""

But don't know how to incorporate it into my script which looks like:


fc = r'.....'

rows = arcpy.UpdateCursor(fc)


Y = 1
prev_X = "" #<=========== DOESN'T WORK
for row in rows:
if row.X == 1:
Y = 1
row.Y = Y
rows.updateRow(row)

while row.X == 0 and prev_X == 1:
Y = 2

row.Y = Y
rows.updateRow(row)

while row.X == 0 ande prev_X == 0:
Y = 0
row.Y = Y
rows.updateRow(row)
rows.next()

row.X = X

rows.updateRow(row)

del row, rows

Answer



Instead of using while statements, I'd go with your idea of using a prevX var. The key is that you declare the variable after you know the value of X is for each turn through the loop.


By declaring prevX in each of your control structures (if or elif statement), you know what the value of X was in that loop.


This is just a nested conditional (you could accomplish this by using and between conditionals too).


fc = r'.....'
rows = arcpy.UpdateCursor(fc)


for row in rows:

if row.X == 0:
row.Y = 1
rows.updateRow(row)
prevX = 0 #Now the script knows that the last value of X was 0

elif row.X == 1:
if prevX == 1:
row.Y = 2

rows.updateRow(row)
prevX = 1 #Now the script knows that the last value of X was 1

elif prevX == 0:
row.Y = 0
rows.updateRow(row)
prevX = 0 #Now the script knows that the last value of X was 0

In your question, you didn't state what the value of Y would be if X = 0 and there was no previous value of X (i.e. if this was the first row).


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