1

I have point layer, counties border area layer and I want to pick different number of points within different areas (counties) but from existing point layer - e.g. county A -> 10, county B -> 6, etc.

I'm wondering if code delivered by @Emil Brundage in Randomly subsetting X% of selected points using ArcPy? could be changed to use field values and area borders (like in Create Random Points tool) instead of one indicated count value to select random points from whole point layer. Because this code does only this.

Did I describe it clearly now?

def SelectRandomByCount (layer, count):
import random
layerCount = int (arcpy.GetCount_management (layer).getOutput (0))
if layerCount < count:
    print "input count is greater than layer count"
    return
oids = [oid for oid, in arcpy.da.SearchCursor (layer, "OID@")]
oidFldName = arcpy.Describe (layer).OIDFieldName
path = arcpy.Describe (layer).path
delimOidFld = arcpy.AddFieldDelimiters (path, oidFldName)
randOids = random.sample (oids, count)
oidsStr = ", ".join (map (str, randOids))
sql = "{0} IN ({1})".format (delimOidFld, oidsStr)
arcpy.SelectLayerByAttribute_management (layer, "", sql)
KaBi
  • 55
  • 5

1 Answers1

1

With a few modifications, it can be done. Eventually you need to specify the number of random point by the attribute (i.e. selection_dict below). Here is an example:

import arcpy

def SelectRandomByCount (layer, count):
    import random
    layerCount = int (arcpy.GetCount_management (layer).getOutput (0))
    count=layerCount if layerCount < count else count
    oids = [oid for oid, in arcpy.da.SearchCursor (layer, "OID@")]
    return random.sample (oids, count)

selection_dict={"County A":10,"County B":6}
aggregate_random_oids=[]

for k,v in selection_dict.items():
    arcpy.SelectLayerByAttribute_management(my_layer,"NEW_SELECTION","%s = '%s'" %(arcpy.AddFieldDelimiters(my_layer.dataSource,"County_Name"),k))
    aggregate_random_oids+=SelectRandomByCount (my_layer, v)

oidFldName = arcpy.Describe (my_layer).OIDFieldName
path = arcpy.Describe (my_layer).path
delimOidFld = arcpy.AddFieldDelimiters (path, oidFldName)
oidsStr = ", ".join (map (str, aggregate_random_oids))
sql = "{0} IN ({1})".format (delimOidFld, oidsStr)
arcpy.SelectLayerByAttribute_management (my_layer, "", sql)
fatih_dur
  • 4,983
  • 2
  • 16
  • 35