Answers:
这是一个python函数,它将基于百分比选择图层中的随机特征,而忽略当前选择:
def SelectRandomByPercent (layer, percent):
#layer variable is the layer name in TOC
#percent is percent as whole number (0-100)
if percent > 100:
print "percent is greater than 100"
return
if percent < 0:
print "percent is less than zero"
return
import random
fc = arcpy.Describe (layer).catalogPath
featureCount = float (arcpy.GetCount_management (fc).getOutput (0))
count = int (featureCount * float (percent) / float (100))
if not count:
arcpy.SelectLayerByAttribute_management (layer, "CLEAR_SELECTION")
return
oids = [oid for oid, in arcpy.da.SearchCursor (fc, "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)
将其复制/粘贴到ArcMap中的python shell中。
然后在shell中键入SelectRandomByPercent ("layer", num)
,这layer
是图层名称,并且num
是百分比的整数。
根据要求找到子集选择的变体:
def SelectRandomByPercent (layer, percent):
#layer variable is the layer name in TOC
#percent is percent as whole number (0-100)
if percent > 100:
print "percent is greater than 100"
return
if percent < 0:
print "percent is less than zero"
return
import random
featureCount = float (arcpy.GetCount_management (layer).getOutput (0))
count = int (featureCount * float (percent) / float (100))
if not count:
arcpy.SelectLayerByAttribute_management (layer, "CLEAR_SELECTION")
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)
最后,还有一种变化,可以按计数而不是百分比来选择层:
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)
random.sample()
。
sql
参数的字符串长度是否存在已知限制?
通常,我还建议使用blah238讨论的空间生态工具。
但是,您可以尝试的另一种方法是添加一个名为Random的属性来存储随机数:
然后,使用该属性的字段计算器和Python Parser,使用以下代码块:
import random
def rand():
return random.random()
见下图:
这将创建介于0和1之间的随机值。然后,如果要选择20%的特征,则可以选择Random值小于0.2的特征。当然,这将与许多功能一起更好地工作。我创建了一个只有7个要素作为测试的要素类,并且所有值都不小于0.2。但是,您似乎具有很多功能,所以没关系。
您可以尝试使用霍斯工具:http : //www.spatialecology.com/htools/rndsel.php
请注意,现有选择不被接受,因此您必须首先从现有选择中制作要素图层。