Sunday, 26 January 2020

arcpy - Remove duplicates from a field


I need to remove duplicates from a field named "Intersecti"


enter image description here


Here is my code. I used list..set. It's not removing any duplicates.


import arcpy
duplicates = "G:\\xStreetNew\\Duplicates.shp"
duplicates_List = []

with arcpy.da.SearchCursor(duplicates, ['Intersecti']) as Cur:
for row in Cur:
duplicates_List.insert(0,row[0])
duplicates_List = list(set(duplicates_List))
print duplicates_List

Answer



You need to:



  • Use an update cursor

  • Split the string into a list


  • Remove duplicates

  • Put the list back into a string

  • Assign the string to that row/field

  • Apply the update


Try this:


import arcpy
duplicates = "G:\\xStreetNew\\Duplicates.shp"

with arcpy.da.UpdateCursor(duplicates, ['Intersecti']) as cur:

for row in cur:
row[0] = ','.join(list(set(row[0].split(','))))
cur.updateRow(row)

Or--for clarity-- you could replace the jumbled, multi-operation line, like this:


import arcpy
duplicates = "G:\\xStreetNew\\Duplicates.shp"

with arcpy.da.UpdateCursor(duplicates, ['Intersecti']) as cur:
for row in cur:

v = row[0]
v = v.split(',')
v = list(set(v))
v = ','.join(v)
row[0] = v
cur.updateRow(row)

No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...