13

I am needing to auto increment a field based on groups within a feature class. I have 8 plots within a given polygon and I need to assign them an ID from 1-8 for each set of plots within each polygon. The polygon would have its own unique ID number to be used to group the plots.

I assume it would be an alteration of this:

rec=0
def autoIncrement():
 global rec
 pStart = 1 
 pInterval = 1 
 if (rec == 0): 
  rec = pStart 
 else: 
  rec = rec + pInterval 
 return rec
0

1 Answer 1

14

Field calculator for Python

d={}
def GroupOrder(groupID):
  if groupID in d: d[groupID]+=1
  else: d[groupID]=1
  return d[groupID]

---------------------------

GroupOrder( !locality! )

Change !locality! to relevant field.

UPDATE: This variation of expression:

d={}
def GroupOrder(groupID):
  N=d.get(groupID,0);N+=1
  d[groupID]=N
  return N

Should work much faster on large datasets.

6
  • If the GroupOrder function were to be used in a stand-alone python script, the GroupOrder function would be the code block argument and the GroupOrder( !locality! ) would be the 'expression' argument. Mar 11, 2020 at 3:21
  • In script it is: a) create dictionary b) update cursor on 2 fields group and one to be populated. 3-5 lines of code.
    – FelixIP
    Mar 11, 2020 at 3:29
  • 1
    I neglected to mention in my comment that those arguments would be included in the arcpy calculate field tool: arcpy.CalculateField_management(inTable, fieldName, expression, "PYTHON_9.3", codeblock) if used in a stand-alone script. Thanks for describing the steps of a different approach to using your code in a stand-alone script. Mar 11, 2020 at 3:46
  • All good. Anyway I am under impression that da cursor is much faster than field calculator.
    – FelixIP
    Mar 11, 2020 at 4:02
  • I want to do the same but group by ID column in shapefile and it is not working. I have replaced groupID by ID - d={}def GroupOrder( !ID! ): N=d.get( !ID! ,0);N+=1 d[ !ID! ]=N return N
    – MapQuest
    Sep 15, 2020 at 12:43

This site is temporarily in read-only mode and not accepting new answers.

Not the answer you're looking for? Browse other questions tagged .