0

in my work, I have to find the features having duplicate values of field "ID" and leave just one identical value by updating blank values in rest of the features.

My code for an add-in is:

import arcpy
from arcpy import env
import pythonaddins

class ButtonClass1(object):
    """Implementation for Remove_Duplicate_ID_addin.button (Button)"""
    def __init__(self):
        self.enabled = True
        self.checked = False
    def onClick(self):
        mxd = arcpy.mapping.MapDocument("CURRENT")
        layers = arcpy.mapping.ListLayers(mxd)
        for layer in layers:
            desc = arcpy.Describe(layer)
            path1 = str(desc.path) + r"\outstat"

            env.workspace = desc.path
            arcpy.Statistics_analysis(layer, path1, [["ID","COUNT"]], "ID")

            j = 0
            with arcpy.da.SearchCursor(path1, ["ID", "COUNT_ID"]) as cur:
                for row in cur:
                    if (len(row[0]) > 3) and int(row[1]) > 1:
                        print(row[0])
                        print(row[1])
                        arcpy.SelectLayerByAttribute_management(layer, "NEW_SELECTION", '"ID" = ' + "'" + row[0] + "'")
                        i = 1
                        with arcpy.da.UpdateCursor(layer.name, "ID") as outs:
                            for ids in outs:
                                while i < int(row[1]):
                                    ids = ("",)
                                    outs.updateRow(ids)
                                    print(i)
                                    j += 1
                                    i += 1
                            print("ID: '" + str(row[0]) + "' present in " + str(row[1]) + " and removed from " + str(i -1) + " features.")
            print("Total " + str(j) + "features corrected in " + str(layer.name) + ".")

But when I run the code, it just update only one feature with blank value and leave rest of them as it is.

What is a workaround for this?

2

Create a set and populate it with values using a cursor. If you find a value that's already in the set update your table.

ids = set ()
with arcpy.da.UpdateCursor(layer.name, "ID") as outs:
    for idVal, in outs:
        if idVal in ids:
            row = ("",)
            outs.updateRow (row)
            continue
        ids.add (idVal)

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.