Calculating counting field

1422
5
Jump to solution
03-07-2017 10:02 PM
KelvinMwakomo
Occasional Contributor

Hello guys,

Assistance please,

I have a table below;

From there i created a new field "code" so i want to calculate a sequential numbers based on how much the "Unique_no" appears like the one below;

Regards,

Kelvin.

0 Kudos
1 Solution

Accepted Solutions
NeilAyres
MVP Frequent Contributor

You could do this with an update cursor and a dictionary, something like this...

data_dict = {}
with arcpy.da.UpdateCursor(fcName, ["Unique_no", "Code"]) as Cur:
    for row in Cur:
        if row[0] in data_dict:
            # increment counter
            data_dict[row[0]] += 1
        else:
            data_dict[row[0]] = 1
        # update code
        cnt = dat_dict[row[0]]
        row[1] = cnt
        Cur.updateRow(row)

View solution in original post

5 Replies
NeilAyres
MVP Frequent Contributor

You could do this with an update cursor and a dictionary, something like this...

data_dict = {}
with arcpy.da.UpdateCursor(fcName, ["Unique_no", "Code"]) as Cur:
    for row in Cur:
        if row[0] in data_dict:
            # increment counter
            data_dict[row[0]] += 1
        else:
            data_dict[row[0]] = 1
        # update code
        cnt = dat_dict[row[0]]
        row[1] = cnt
        Cur.updateRow(row)
KelvinMwakomo
Occasional Contributor

Thanks Neil,

See if I'm wrong somewhere because i am not good in python.

0 Kudos
NeilAyres
MVP Frequent Contributor

Firstly try and run this as a script in IDLE or pyscripter or something.

You have the indentation wrong. The line starting else:

Should be at the same level as the if:

Indentation in python is a crucial part of the language syntax.

Try doing a bit of reading up on python first.

NeilAyres
MVP Frequent Contributor

And the last 3 lines also at the same indentation level as the if:

0 Kudos
JoshuaBixby
MVP Esteemed Contributor

Using defaultdict allows the code to be simplified/condense a bit:

from collections import defaultdict

data_dict = defaultdict(int)
with arcpy.da.UpdateCursor(fcName, ["Unique_no", "Code"]) as cur:
    for uniq, code in cur:
        data_dict[uniq] += 1
        cur.updateRow([uniq, data_dict[uniq]])‍‍‍‍‍‍