0

I am trying to add a field in a feature class that is populated with the number (or count) of how many other features in that same feature class have the same attribute value in a particular field. For example, I have a feature class of gas wells that has an attribute field with the wells pad name called "PadName". I want to create a field in this same feature class with the total count of how many wells share that same "PadName".

I am able to get the count of how many features share that same pad name but I am struggling to populate the newly create "COUNT" field with that number?

Below is my current code.

import arcpy, os, sys

fc = r"GIS\mygeodatabase.gdb\wells"
field = "PadName"
count = "COUNT"

try:
    arcpy.AddField_management(fc, "COUNT", "TEXT", "", "", "10", "", "NULLABLE", "NON_REQUIRED", "")
    print "Successfully Created Count Field!"
except:
    print "Failed to Create Count Field"


Occurances = []
with arcpy.da.SearchCursor (fc, field) as cursor:
    for row in cursor:
        Occurances.append (row[0])

for i in set(Occurances):
    icount = Occurances.count(i)
    print str(i) + ":", icount, "features"
    with arcpy.da.UpdateCursor(fc,count) as cursor:
        for row in cursor:
            row[0] = Occurances.count(i)
            cursor.updateRow(row)

It is populating my new "COUNT" field that I created but it is giving every feature a value of "5" for some reason?

2

First count the instances of each value in a dictionary in the format {"value": count} using a Search Cursor, then in an Update Cursor check what the value is, then write the count to the new field.

occurrences = dict() # Create a dictionary to count the values
with arcpy.da.SearchCursor(fc, field) as cursor:
    for row in cursor:
        # Count the number of times each value occurs in the field
        occurrences[row[0]] = occurrences.get(row[0], 0) + 1

with arcpy.da.UpdateCursor(fc, [field, count]) as cursor:
    for row in cursor:
        row[1] = occurrences[row[0]]
        cursor.updateRow(row)
| improve this answer | |

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.