1

My requirement is to create auto increment numbers in the field2 based on the values in field1. But if field1 having same for more than one row, Increment number also remains same.

ex:

field1         |  field2
479049.620600  |  1  
479049.620600  |  1  
478611.065000  |  2  
478732.117500  |  3  
478890.969400  |  4  
478890.969400  |  4  
478890.969400  |  4  
479046.462900  |  5  
478576.747800  |  6  

I have searched and got some code but it does not meet my requirement.

import arcpy
from arcpy import env

path = r"C:\SOFTWARE\Shapefiles\shp\Points.shp"
arcpy.env = path

rows = arcpy.arcpy.UpdateCursor(path)
myList = []

i = 0

for row in rows:
    if i == 0:
        value = row.X
        myList.append(value)
    i += 1
    print value, i
    if row.ID != value:
        value = row.X
        myList.append(value)
    rows.updateRow(row)
del rows
5
  • Welcome to GIS SE! As a new user please take the tour to learn about our focused Q&A format. Please edit your question to include details about what happens when you run your code snippet that you say doesn't meet your requirement.
    – Midavalo
    Mar 11, 2017 at 17:13
  • Do you mean you want to increment field2 based on the value in field1 so if the value in field1 already exists it reuses the same number for field2?
    – Midavalo
    Mar 11, 2017 at 17:14
  • Yes Midavalo. if number in field1 exits two times, increment number also same.
    – Arb
    Mar 11, 2017 at 17:16
  • Field1 field2(increment field) 152 1 145 2 145 2 125 3 125 3 178 4
    – Arb
    Mar 11, 2017 at 17:19
  • 1
    Please edit your question to include clarification or more info, rather than using comments. Comments are for potential answerers to ask for more info, your response should be as an edit to your question.
    – Midavalo
    Mar 11, 2017 at 17:31

1 Answer 1

2

Create a python dictionary to store your field1 values with the increment value entered into field2 for that value. In your cursor look up if the field1 already has an increment value, and if it does use that value. If it doesn't then use the increment i and add that to the dictionary.

import arcpy
i = 1
incDict = dict()
with arcpy.da.UpdateCursor(path , ["field1", "field2"]) as cursor:
    for row in cursor:
        if row[0] in incDict:
            row[1] = incDict[row[0]]
        else:
            row[1] = i
            incDict[row[0]] = i
            i += 1
        cursor.updateRow(row)

enter image description here

Note I've used the same numbers as your example, but not in the same order to show that the increment number will be reused when the field1 value is reused.

1
  • Excellent answer. Thank you Midavalo. it helps me a lot and save the time also.
    – Arb
    Mar 11, 2017 at 17:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.