Random Polygon Selector by Attribute/Area

691
1
07-22-2011 08:36 AM
RustyGriffin
New Contributor
Hello all,

I am very new to Python scripting and am trying to create a tool to randomly select a sub set of polygons by an attribute and equaling ~ 10% of the total attribute area.  It seems that this shouldn't be so difficult but it is causing me a lot of problems.

Please help.
Tags (2)
0 Kudos
1 Reply
GerryGabrisch
Occasional Contributor III
Here is the code to populate an attribute in the attribute table with a 0 or 1 for 5% of your records.  If you want to select 5% of those records that have some other attribute value, then just insert a select by attribute where I have it marked, then only 5% of the selected records will be assigned a 1.



'''Selects a random number of records from a feature class and populates a
   user-defined field with either a 1 or a 0 based on the input parameters.  For
   example, if percent_to_include is set to 5, then a random ~5 percent of the
   records will be asigned a value of 1, the rest a value of 0.
'''
try:
    
    import operator, os, random, traceback, sys, arcpy

    ##Path to the feature class.
    fc = r"Z:\GISpublic\GerryG\RestorationandMitigationConcept\20110425IvyPlotMonitoring\transects.shp"
    ##The attribute to populate with 1 or 0...
    attribute = r"issample"
    ##The percent threshold to include as a random selection.
    percent_to_include = 5

    ##INSERT YOUR SELECT BY ATTRIBIUTE HERE

    uc = arcpy.UpdateCursor(fc)
    for row in uc:
        x = random.random() * 100
        #arcpy.AddMessage(x)
        if x <= percent_to_include:
            row.setValue(attribute, 1)
        else:
            row.setValue(attribute, 0)
        uc.updateRow(row)
    print "Done"
except:
    tb = sys.exc_info()[2]
    tbinfo = traceback.format_tb(tb)[0]
    pymsg = "PYTHON ERRORS:\nTraceback info:\n" + tbinfo + "\nError Info:\n" + str(sys.exc_info()[1])
    print pymsg + "\n"
0 Kudos