Adding sequential number according to change value of next field using ArcPy

3691
4
03-15-2016 02:55 PM
AngelaKim2
New Contributor

My goal is to create and fill data like (Field 3) from (Field 1) using the Field Calculator.

I was able to assigning sequential numbers using ArcPy code out there, but it gave me results of (Field 2).

I assume I need double loop to achieve the result of (Field 3), but the problem is I'm not familiar with ArcPy at all.

It would be great if you help me out with ArcPy or even point the sample code I can look at.

Thanks!

AK

Field 1Field 2Field 3
111
122
133
144
251
262
371
382
393
3104
0 Kudos
4 Replies
DarrenWiens2
MVP Honored Contributor

If you post the original code you used for Field 2, we can go from there.

0 Kudos
DanPatterson_Retired
MVP Esteemed Contributor

is that the limit of the examples? does the example define all the rules?

  • field 1, 4x, 2x, 4x with integer sequence
  • field 2 sequence from 1-19 based on sequence in the previous
  • field3  1,2,3,4  1,2   1,2,3,4 to match the sequencing in field 1

so the next sequence would be

field 1    4 4 4 4 5 5 6 6 6 6

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

field 3   1 2 3 4 1 2 1 2 3 4

just to check there are no hidden rules or exceptions

AngelaKim2
New Contributor

Hi Darren,

This is the code I used for filling the Field 2.  (I have ArcGIS 10.3.1 by the way)

Source:  38517 - Create sequential numbers in a field using Python in the Field Calculator

Pre-Logic Script Code:

rec=0

def autoIncrement():

global rec

pStart = 1 

pInterval = 1

if (rec == 0): 

  rec = pStart 

else: 

  rec += pInterval 

return rec

Expression:

autoIncrement()

I have a vague idea of having double loop of entering sequential number to Field 3 as number changes in Field 1.

rec=0

field1 = 0

def autoIncrement():

global rec

global field 1

LOOP1 field1 +=1

      LOOP2 rec += 1

      END LOOP2

     return rec

END LOOP1

I appreciate your help!

0 Kudos
DarrenWiens2
MVP Honored Contributor

Here's kind of a simple/complex way to do it:

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

expression: myFunc(!Field_1!)

edit: I had a variable named 'class', which may be a reserved word.