I feel like I've tried so many iterations of this, can anyone assist with how to use ArcPy to selected layer by attribute then delete selected layer? I think my SQL query is incorrect?
import arcpy
import pandas as pd
import numpy as np
pid_field = ["pid"]
target = arcpy.da.TableToNumPyArray(Master_Subjects, pid_field)
Master_Subjects = r"C:\Users\dsser\Documents\ArcGIS\Projects\MyProject1\Master_Subjects.shp"
target_pid = target[0]["pid"]
# just selecting a random pid here from the Master_Subjects shapefile to see if I can get the select by attribute to work.This is a shapefile feature class with point geometry.
# Also, target_pid is an integer
target_pid = target[0]["pid"]
query = "'" "subject_pid" = target_pid "'"
arcpy.SelectLayerByAttribute_management(Master_Subjects, "NEW_SELECTION", query)
arcpy.DeleteFeatures_management(Master_Subjects)
1 Answer 1
I see, your target_pid is a number and not a field, in which case the comment by BERA is correct.
Try it like this:
pid_field = "pid" # don't need brackets here
target = arcpy.da.TableToNumPyArray(Master_Subjects, pid_field)
Master_Subjects = r"C:\Users\dsser\Documents\ArcGIS\Projects\MyProject1\Master_Subjects.shp"
Master_Layer = arcpy.MakeFeatureLayer_management(Master_Subjects) # Must be a layer for Select Layer by Attribute
# just selecting a random pid here from the Master_Subjects shapefile to see if I can get the select by attribute to work.This is a shapefile feature class with point geometry.
# Also, target_pid is an integer
target_pid = target[0]["pid"]
query = "{} = {}".format(pid_field,target_pid)
print "{} features before selection".format(arcpy.GetCount_management(Master_Layer).getOutput(0))
arcpy.SelectLayerByAttribute_management(Master_Layer, "NEW_SELECTION", query)
print "{} features after selection".format(arcpy.GetCount_management(Master_Layer).getOutput(0))
arcpy.Delete_management(Master_Layer) # layer object gone now
To select from a layer the input object must be a layer and not a feature class, use arcpy.MakeFeatureLayer_management to derive a layer from the feature class; I've added GetCounts to show the count of features before and after selection.
If you truly intend to delete the features permanently from the feature class selected by your query then the tool you are using (delete features) is correct.
Explore related questions
See similar questions with these tags.
query = """{0}={1}""".format(arcpy.AddFieldDelimiters(datasource=somelayer, field="subject_pid"),target_pid)
print type(target_pid)
? SelectLayerByAttribute wants a layer as input, not shapefile. Use MakeFeatureLayer and then Select on this. Your Query has syntax errors, trya = "'" "subject_pid" = target_pid "'"
in console and see. Use format like i showed you.