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)
  • What happens when you run your code snippet? – PolyGeo Dec 5 '17 at 9:48
  • I've edited a little my question, maybe this time it would be easier to understand me :) – KaBi Dec 5 '17 at 10:01
  • The desired number of selected Points are in a column in the county polygons? – BERA Dec 5 '17 at 10:36
  • @BERA - yes, in that layer I have county name and number of points that are suppose to be picked. – KaBi Dec 5 '17 at 11:19
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)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.