How to count the number of features with the same value for an attribute

6276
11
Jump to solution
01-16-2018 09:15 AM
FedericoVélez
New Contributor

I need a way in python to have the Count1 (in the image).

 

I have already did it using excel, but due to the client requirement it must be done either in modelbuilder or in a python scrit, i currently have the script to have the Count2, so i only need the Count1

Note: the data displayed in the image is not the actual data but a example)

Tags (3)
0 Kudos
11 Replies
JamesMacKay3
Occasional Contributor

If I understand correctly this might do the trick in the field calculator...  In the Pre-Logic Script Code try this:

projectCounts = {}

def getCount(project):
    if not project in projectCounts:
        projectCounts[project] = 0
    projectCounts[project] += 1
    return projectCounts[project]
‍‍‍‍‍‍‍

And in the textbox below set Count1 =

getCount(!ProjectName!)
0 Kudos
XanderBakker
Esri Esteemed Contributor

In case you have a featureclass (or table) with only the Project name info and the output fields (count1 and count2) already present in the featureclass you could do something like this:

def main():
    import arcpy
    tbl = r'C:\Identity\Supremacy\Ultimatun\Legacy\Bourne' # path to table or featureclass
    fld_proj = 'ProjectName'
    fld_cnt1 = 'Count1'
    fld_cnt2 = 'Count2'

    # update cycle 1 (asuming data is sorted)
    flds = (fld_proj, fld_cnt1)
    prev_proj = None
    cnt = 0
    dct = {}
    with arcpy.da.UpdateCursor(tbl, flds) as curs:
        for row in curs:
            proj = row[0]
            if proj != prev_proj:
                seq = 1
            else:
                seg += 1
            dct[proj] = seq
            row[1] = seq
            curs.updateRow(row)

    # update cycle 2
    flds = (fld_proj, fld_cnt2)
    with arcpy.da.UpdateCursor(tbl, flds) as curs:
        for row in curs:
            proj = row[0]
            if proj in dct:
                row[1] = dct[proj]
            else:
                # this should not happen
                row[1] = -1
            curs.updateRow(row)

if __name__ == '__main__':
    main()