Field Calc Sequential Number based on another column

10-13-2020 07:50 AM
New Contributor II

I need to populate a column (Level4Code) with the field calculator that counts sequentially based on another column (Level3Name) and includes 4 digits. Here is an example of a table that's already populated correctly:



Agar Malwa0001
Agar Malwa0002

The out of the box sequential code does not do it correctly since it doesn't loop based on any other column.

So far, I've tried this code snippet to count but I am not getting the results I need. This only seems to count the total number of times that word in Level3Name is present:

  1. dict = {} # make a dictionary  
  2. def myFunc(myClass): # this is the function  
  3.   global dict # specify global  
  4.   dict[myClass] = dict.get(myClass, 0) + 1 # if the dictionary key for the value exists, add 1 to it. If not, make it 0.  
  5.   return dict[myClass] # return the value for that key  

Any suggestions? I am new to Python so any help would be great.

0 Kudos
2 Replies
New Contributor II

Update: Using this python script I was able to have it count properly and populate the needed column. I guess now I just need to know how to set it to have 4 digits with leading 0's (ie 0001 instead of 1, or 0110 instead of 110). Any suggestions?

tbl = r'C:\my\data.gdb\table'

data_dict = defaultdict(int)

with arcpy.da.UpdateCursor(tbl, ["Level3Name", "Level4Code"]) as cur:

    for uniq, code in cur:

        data_dict[uniq] += 1

        cur.updateRow([uniq, data_dict[uniq]])

0 Kudos
MVP Esteemed Contributor

As you have learned, or maybe just coincidentally avoided, using Field Calculator for creating sequential numbering runs into problems if the sequencing doesn't line up with the ObjectID sequence.

Regarding your follow-up question, do you want to have the data stored as "000x" etc... or do you just want the formatting for a table you are looking at to be that way?  If the former, you need Level4Code to be a string field and use string formatting.  If the latter, you can create a custom number formatting for that field in the table in Pro.

The following should work for string formatting:

cur.updateRow([uniq, "{:0>4}".format(data_dict[uniq])])