ArcPy – How to Create Sequential Numbers in a Field Automatically

arcpyautoincrementexpressionfield-calculatorpython

I would like to create sequential numbers in a field called "virtual _Li".

enter image description here

I have used the field calculator using def autoincrement() function and manually calculate the interval number.
https://support.esri.com/en/technical-article/000011137

enter image description here

But I would like to have it in python.

The start point should be always the number in “Z_2018” that has “0” in “First_Dist” (Start = 1.006).
End number is the number in “Z_2018” that has the Maximum number in “FIRST_DIST” (End = 1.04).

The interval is:( (End) – (Start) ) / ( max in “FIRST_DIST” field/a constant number )

Constant number is always = 0.15

Start and end number can be + or number.

In this case interval is 0.002875793

( (1.040) –  (1.006) ) / (1.773424/0.15) = 0.002875793

First create a field:

arcpy.AddField_management(ProfileGraph1WR1, "Virtual_Li", "DOUBLE", 10, 3)

then I need to create a “codeblock” and “Expression” which I don’t know How.

Best Answer

Code Example 3 on Esri's documentation for Calculate Field is probably the closest to your question.

Since you have up through the AddField, the code below proceeds from there based on that example.

with arcpy.da.SearchCursor("ProfileGraph1WR1", ["First_Dist", "Z_2018"]) as cursor:
    firstdistvals = dict()       
    for row in cursor:
        if row[0] == 0: 
            startval = row[1]
        firstdistvals[row[0]] = row[1]
    maxval = max(firstdistvals.keys())
    endval = firstdistvals[maxval]


# Set local variables
inTable = "ProfileGraph1WR1"
fieldName = ""Virtual_Li"
expression = "autoIncrement({}, {}, {})".format(startval, endval, maxval)  

codeblock = """
    rec = 0
    def autoIncrement(start, end, maximum):  
        global rec
        const = 0.15
        pStart = float(start)
        pInterval = (float(end) – float(start))  / (float(maximum)/const)
        if (rec == 0):
            rec = pStart
        else:
            rec += pInterval
        return rec"""

# Execute CalculateField 
arcpy.CalculateField_management(inTable, fieldName, expression, "PYTHON_9.3", codeblock)
Related Question