ArcPy – How to Select Random Points from Feature Class

arcpypointrandomselect

I have shapefile that includes 49 points (wells). I want to create 100 networks that include 20 randomly selected points from first network. When I used create random point tool, Some networks were duplicates. How can I create non-repetitive networks?

Best Answer

Since we need to compile a list of IDs for an SQL IN operator anyway, let's use that string as the comparison basis to generate the unique lists...

import random
import arcpy

numSets   = 100
setSize   = 20
sourceFC  = r'D:\gis_se\pick49.shp'
outputGDB = r'D:\gis_se\picked.gdb'

# Extract all IDs
rawIDs = sorted([row[0] for row in arcpy.da.SearchCursor(sourceFC,'OID@')])

# Compile unique sets
resultSets = []
while (len(resultSets) < numSets):
    candidate = list(rawIDs)
    random.shuffle(candidate)
    subset = ','.join([str(id) for id in sorted(candidate[:setSize])])
    if (subset not in resultSets):
        resultSets.append(subset)

# Export the copies to GDB (or not)
print("\n".join(sorted(resultSets)))

When testing with "generate 10 sets with 5 picked from 10" I was able to generate duplicate candidates, but when I moved up to "generate 100 sets with 20 picked from 49" I wasn't, but even if your random generator is cruel, this won't generate duplicates.