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"
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.
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.
Or I have several blogs on how to extract unique values quickly using numpy
What about doing a summary statistics on the table? Very straight - forward.
Analysis Tools >> Statistics >> Summary Statistics
Best Regards,
Jim