1

I am trying to recalculate a value for a field using arcpy.CalculateField_management() using a tricky expression. Currently, I am recalculating one field named REACH_ID, using another field ('CO_FIPS') and them adding "01" + '!REACH_ID[-5:]'

arcpy.CalculateField_management(layer_output,'REACH_ID','!CO_FIPS! + "01" + !REACH_ID![-5:]','PYTHON')    

So if I had a REACH_ID = 440030100008 and a CO_FIPS = 44023, it would recalculate as 440230100008. Now what I want to do is simply replace the '!REACH_ID[-5:]' with an incrementor. So if 440030100008 was the first REACH_ID in my attribute table, I want to make replace 00008 with 00001 and then for the next row, I want to add 00002, and so on. The first problem is that its tricky creating a string incrementor, but I have overcome that issue. I can use something like this (using a 'counter'):

x = '00000'
for i in range(0, 10):
    x = str(int(x) + 1).zfill(len(x))
    print(x)

or as a function where length would be the row count of the feature, layer_output :

x = '00000'
f_length = arcpy.GetCount_management(layer_output)
def incrementor(counter, length):
    for i in range(0, length):
        counter = str(int(counter) + 1).zfill(len(counter))
        print(counter)

arcpy.CalculateField_management(layer_output,'REACH_ID','!CO_FIPS! + "01" + incrementor(x, f_length),'PYTHON')

But, the problem is...how does one get the incrementor to work inside of the expression in CalculateField_management? Am I going about this the wrong way? I haven't come across any other questions that explain how to achieve this.

gwydion93
  • 1,903
  • 4
  • 28
  • 59
  • 1
    See this https://gis.stackexchange.com/questions/200150/auto-incrementing-field-based-on-groups-within-feature-class/200154#200154 – FelixIP Dec 07 '20 at 21:49

0 Answers0