Select to view content in your preferred language

get unique values for shapefile

3410
4
06-07-2017 02:16 PM
BryanMcPherson1
Deactivated User

I would like to create a set of unique values from a shapefile contained within an arcmap project. Most of the codes I see do this with feature classes and point to a geodatabase. I prefer not to point to anything outside of my current layers in the project window. How do I go about doing this?

I would like to do the following:

get unique values from a shapefile table save the unique values to an array (for use in a loop) print the unique values out to the screen For this example we'll call the shapefile in the map "location" and the field name "points"

Tags (1)
0 Kudos
4 Replies
JonathanQuinn
Esri Notable Contributor

You'll probably want to start by following the examples for a SearchCursor, but instead of setting the path to the data, you're deriving it based on the layer and the layers dataSource property.  Then, you can begin iterating over the values within the Search Cursor and either add it to a list if it doesn't exist already or use set() to get unique values.

>>> usingSet = []
>>> usingUnique = []
>>> mxd = arcpy.mapping.MapDocument("CURRENT")
>>> df = arcpy.mapping.ListDataFrames(mxd)[0]
>>> for layer in arcpy.mapping.ListLayers(mxd):
...     lyrPath = layer.dataSource
...     with arcpy.da.SearchCursor(lyrPath, ['ID']) as cursor:
...         for row in cursor:
...             if not row[0] in usingUnique:
...                 usingUnique.append(row[0])
...             usingSet.append(row[0])
... print(usingSet)
... print(set(usingSet))
... print(usingUnique)
... 
[1, 1, 2, 2, 3, 4]
set([1, 2, 3, 4])
[1, 2, 3, 4]‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍

If you're going to iterate over multiple layers, you'll need to look into looping through the fields using ListFields to create the fields list for the cursor.

JoshuaBixby
MVP Esteemed Contributor

I agree with Jonathan Quinn‌, read up on ArcPy Data Access cursors if you haven't already.  If you are only interested in finding unique values in one field, the Counter object is what you want:

>>> from collections import Counter
>>> with arcpy.da.SearchCursor("locations","points") as cur:
...     count = Counter(cur)
... 
>>> 

Not only will you get the unique values, you will get their counts as well.

DanPatterson_Retired
MVP Emeritus

Or I have several blogs on how to extract unique values quickly using numpy 

0 Kudos
JimCousins
MVP Regular Contributor

What about doing a summary statistics on the table? Very straight - forward.

Analysis Tools >> Statistics >> Summary Statistics

Best Regards,

Jim

0 Kudos