Sunday, 2 April 2017

arcgis desktop - What is Python equivalent of ModelBuilder's Iterate Feature Selection?


My data consists of two featureclasses:



  1. Points = points representing trees

  2. Polygons = Polygons representing % canopy area by area. Each polygon in the FC has a % canopy measurement in the attributes.



I am trying to accomplish the following:



  1. Select points underneath polygon features

  2. For the points under each polygon, delete X% of the points based on the polygon attribute


The screenshot (Figure 1) shows a ModelBuilder only tool called Iterate Feature Selection. What is the correct Python scripting method to iterate through features in a feature class in order to pass the feature off to the SelectLayerByLocation_management command?


Figure 2 shows the output of the select by location. All 4 layers are the same, which will be a problem when I try and delete points by the canopy % measurement.


This is what I have tried so far:


import arcpy
from arcpy import env


env.overwriteOutput = True
env.workspace = r'C:\temp_model_data\OutputData'
outWorkspace = env.workspace

# The polygons have canopy % data in attributes
polygons = r'C:\temp_model_data\CanopyPercentages.shp'
points = r'C:\temp_model_data\points_20_2012.shp'

if arcpy.Exists("pointsLayer"):

print "pointsLayer exists already"
else:
arcpy.MakeFeatureLayer_management (points, "pointsLayer")
print "pointsLayer created"

count = 1

#Create a search cursor to step through the polygon features
polys = arcpy.da.SearchCursor(polygons, ["OID@", "SHAPE@"])


for poly in polys:

# Create a name for the polygon features
count = count + 1
featureName = "polygon_" + str(count)
print featureName

# Select points that lie under polygons
arcpy.SelectLayerByLocation_management('pointsLayer', 'intersect', polygons)
arcpy.SaveToLayerFile_management('pointsLayer', outWorkspace + featureName + ".lyr", "ABSOLUTE")


# Add the random point selection script here...

# Delete selected points within each polygon based on the % canopy cover...

Figure 1 enter image description here


Figure 2 enter image description here



Answer



A SearchCursor in arcpy is the most direct route for accomplishing this:


import arcpy


fc = "c:/data/base.gdb/roads"
field = "StreetName"
cursor = arcpy.SearchCursor(fc)
row = cursor.next()
while row:
print(row.getValue(field))
row = cursor.next()

Note that you can use the where_clause property to perform your selection.



No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...