Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Methods to get a unique list of values from a field in a feature class
import arcpy as ap
import numpy as np
import timeit
lyr = ap.mapping.Layer(r"C:\Some\Arb\Folder\test.gdb\test")
field_name = "NAME"
# Method 1: Python
unique_values = list(set(row[0] for row in ap.da.SearchCursor(lyr, field_name)))
# Method 2: numpy array
unique_values = list(np.unique(ap.da.FeatureClassToNumpyArray(lyr, field_name)[:][field_name]))
# Method 3: SQL
unique_values = [row[0] for row in ap.da.SearchCursor(lyr, field_name, sql_clause=("DISTINCT", None))]
# Simple timeit results on 10 000 iterations
# ArcMap console - Method 1
timeit.timeit('list(set(row[0] for row in ap.da.SearchCursor(lyr, field_name)))', number=10000, setup='import arcpy')
# >>> 9.587467149328631
# ArcMap console - Method 2
timeit.timeit('list(np.unique(ap.da.FeatureClassToNumpyArray(lyr, field_name)[:][field_name]))', number=10000,setup='import arcpy;import numpy as np')
# >>> 9.67362132965468
# ArcMap console - Method 3
timeit.timeit('[row[0] for row in ap.da.SearchCursor(lyr, field_name, sql_clause=("DISTINCT", None))]', number=10000, setup='import arcpy')
# >>> 27.613646132727126
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.