ArcGIS Sequential Values – Calculating Sequential Values Based on Boolean Field in ArcGIS

arcgis-desktoparcgis-profield-calculatorpython-parsersequential

I am trying to calculate sequential ID Values (SeqID) based on Boolean field (Boolean) along several rows in attribute table through the field calculator of ArcGIS Pro, Python, (expression and codeblock).

enter image description here

As you can see in the picture above, the ID number only progress in the count when the Boolean switch from zero to one and one to zero.

I have seen a post where someone solve it in Microsoft Excel but I need to do this in ArcGIS Pro. The solution using Excel is in this post (link: https://stackoverflow.com/questions/45703154/increment-counter-based-on-change-in-cell-value)

Best Answer

A simple python script can generate the sequential numbering you require using a Calculate Field tool, I show this below. It works because I declare the variables id and previous as global, so their values persist as the tool steps through the rows of the table.

Calculate field tool

The code block is:

id = 1
previous = -1
def CreateID(BoolVal):
    global id,previous
    if previous == -1:
        # Deal with first value scenario
        previous = BoolVal
        return id
    else:
        # Increment id if BoolVal is not the same as previous
        if BoolVal == previous:
            return id
        else:
            id = id + 1
            previous = BoolVal
            return id 

The code could potentially be written in an even more concise manner but I leave it like this as its much easier to understand the logic.

Related Question