Skip to content

Instantly share code, notes, and snippets.

@cindygis
Created November 15, 2017 12:56
Show Gist options
  • Save cindygis/0df53e593565aee8f92e67e63b73ff35 to your computer and use it in GitHub Desktop.
Save cindygis/0df53e593565aee8f92e67e63b73ff35 to your computer and use it in GitHub Desktop.
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