I used geometry objects and da.searchCursor to check if randomly created points fall within polygon. Now I get True and False of each points that falls within or outside of the polygon. I made a list of them. Now I am facing problem in filtering only the true ones and updating the point features class. I finally need a point point featureclass in geodatabse(I have already created personal geodatabse "mygdb"); that contains all the points that fall within the polygon. Here is the code where, I create a "point" feature class in gdb. I need to update this featureclass with all the true coordinate pair (or points). I have very little knowledge to work with geometry objects.

fc = "C:/Users/pp/Desktop/proj/poly.shp"
fc1 = arcpy.CreateFeatureclass_management(mygdb, "point", "POINT")
polyGeom = arcpy.CopyFeatures_management("poly",arcpy.Geometry())

plist = []
with arcpy.da.SearchCursor(fc1, "SHAPE@") as cursor:
    for row in cursor:
        #print row[0].within(polyGeom[0])
        pp =  row[0].within(polyGeom[0])
    print (plist)enter code here

So you have a bunch of random points and you want to get rid of the ones that aren't in the polygon? You can make layers from both and use the INVERT selection to pick all the points that aren't WITHIN the polygon layer. Then delete those features (the delete tool knows to use the selection if there is one)

# make feature layers from the two source feature classes
arcpy.MakeFeatureLayer_management(fc, "poly_layer")
arcpy.MakeFeatureLayer_management(fc1, "point_layer")  

# select the points outside the polygon by using WITHIN and INVERT
arcpy.SelectLayerByLocation_management ("point_layer", "WITHIN", "poly_layer", "", "", "INVERT")

# delete the selected features

Or as @alex-tereshenkov suggests, just select the features inside the polygon and then save, which you can do by copying the feature. Like the delete tool, the copy tool will also use your selection.

# select the points inside the polygon by using WITHIN 
arcpy.SelectLayerByLocation_management ("point_layer", "WITHIN", "poly_layer")

# copy the selected features to an output feature class
arcpy.CopyFeatures_management("point_layer", "path/to/my/output")

The piece you're missing from your code is to save a list of object IDs, and then use the list with a separate update cursor to decide which to delete. However, it's easier to use either method above.

oid_list = []

with arcpy.da.SearchCursor(fc1, ["SHAPE@", "OID@"]) as cursor:
    for row in cursor:
        # if the SHAPE is inside the polyGeom
        # save the OID in a list
        if row[0].within(polyGeom[0]):

with arcpy.da.UpdateCursor(fc1, "OID@") as cursor:
    for row in cursor:
        if row[0] in oid_list:

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.