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
PolyGeo
65.5k29 gold badges115 silver badges350 bronze badges
asked Jun 27, 2016 at 23:10
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.

answered Jun 28, 2016 at 0:16
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. Commented 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. Commented 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. Commented Mar 11, 2020 at 3:46
  • All good. Anyway I am under impression that da cursor is much faster than field calculator. Commented 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 Commented Sep 15, 2020 at 12:43

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.