1

I am trying to write an ArcPy script that will select X number of rows from a table with N number of objects in it, then output that selection to a new layer or shapefile. I need to be able to specify the number of selections I need at the time I run the script. I am using ArcGIS 10.2 and working with a point FC. Does anyone have any advice?

#import arcpy and set workspace
import arcpy
arcpy.env.workspace = "G:/583/Final/CRL_WaterSurfaces.gdb"

# set feature class and fields variables
fc = "MnEmbPoints"
fields = ["OID@"]

# list all OIDs in data set
with arcpy.da.SearchCursor(fc, fields) as cursor:
    for row in cursor:
        print("{0}".format(row[0]))
  • 1
    What do you have written so far? – Chad Cooper Apr 25 '14 at 19:25
  • Nothing. I am new to python scripting in general. I have considered trying to generate a random number list and then using arcpy.da.SearchCursor to locate all objects with OIDs matching numbers on my list. I do not really know how to use the SearchCursor well though. – user29594 Apr 25 '14 at 19:34
  • I actually had just enough written to print or list all the OIDs in the data set, depending on whether the last line starts with print or list. – user29594 Apr 25 '14 at 19:52
  • What you could do is once you have all the OID's in the list - you can determine the length of the list - then pick a random number between 0 and the length to determine the random index number of your OID – dklassen Apr 25 '14 at 20:07
3

Something like this:

    import arcpy
    import sys
    from random import randint
    num_of_random = sys.argv[0]

    arcpy.env.workspace = "G:/583/Final/CRL_WaterSurfaces.gdb"

    # set feature class and fields variables
    fc = "MnEmbPoints"
    fields = ["OID@"]

    # list all OIDs in data set
    oid_list = []
    with arcpy.da.SearchCursor(fc, fields) as cursor:
        for row in cursor:
            oid_list.append(row[0])

    # Gets length of list
    max_value = len(oid_list)

    # Generates a random number for the index
    oid_list_subset = []
    for x in range(0, num_of_random):
        rand_index = randint(0,max_value)
        oid_list_subset.append(oid_list[rand_index])

# oid_list_subset should now contain your random subset
  • This is not exactly what I need because I need to get a specified number of random points at once, but the second and third code blocks are very helpful. I was trying all morning to figure out how to get the length of the list so that is a huge relief now! Thank you very much. – user29594 Apr 25 '14 at 20:59
  • I will edit it for that! – dklassen Apr 25 '14 at 20:59
3

This script will take an input feature class and select a sample size of n. It will then create a new feature class and append only the selected sample records to the new sample feature class.

This is my first answer so my apologies if the formatting could be improved.

import arcpy, random
from arcpy import env


def randomFeatures(fileGDB, inputfc, outputfc, numFeatures):
    """
    Selects a sample of features from a sample feature class and creates a new feature class with only those samples
    """
    env.workspace = fileGDB
    env.overwriteoutput = True
    arcpy.CreateFeatureclass_management(fileGDB, outputfc, "POINT", inputfc, "#", "#", inputfc)
    featureCount = arcpy.GetCount_management(inputfc).getOutput(0)
    selection = []
    while numFeatures > 0:
        new_selection = random.randrange(0, int(featureCount))
        if new_selection not in selection:
            selection.append(new_selection)
            numFeatures -= 1
        else:
            pass
    # Search Cursor defined for the original dataset
    rows = arcpy.SearchCursor(inputfc)
    # Insert Cursor created to write the selected features
    rows2 = arcpy.InsertCursor(outputfc)
    row_index = 0
    for row in rows:
        if row_index in selection:
            # New row added to the selection shapefile
            row2 = rows2.newRow()
            # Current row from the full dataset written to the output
            rows2.insertRow(row)
        else:
            pass
        row_index += 1
    del row, rows, row2, rows2
    print "Done"

# Replace the arguments with properly escaped full path and total number of features to select
randomFeatures("E:\\Documents\\GIS_DATA\\stratmap_county\\CountyData.gdb", "CountySeats", "CountySeats_Sample", 25)
  • By the way, this is tested in 10.0, since I don't have access to 10.2. It should still work, but I know you have more cursor options in 10.2, so there may be a better way. – UnchartedDrake Apr 25 '14 at 20:21
  • Let me see if I understand this one correctly. Does it create a list of selected features by iterating through the list over and over until it has randomly selected the number I want, then output that to a new file? I think that might be what I am looking for. Can I set the number I want (i.e. the "25") to be a variable that I control. Maybe using argv()? – user29594 Apr 25 '14 at 20:56
  • Sorry, I didn't have a chance to comment the script thoroughly. It takes the total number of features in the shapefile and randomly select n features (in the example 25). It then moves through the shapefile marking those features as selected. It does not create the output shapefile, but you could check the selected features and export based on the 'Selected' column. You can set the desired number of features to anything you want as long as it is less than the total number of features. – UnchartedDrake Apr 25 '14 at 21:12

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.