Geographic Information Systems Asked on November 1, 2021
I have a point shapefile and a polygon shapefile and want to set the field "Present" to 1 if it intersects with the polygon in ArcPy, but I am having trouble with the SQL syntax for select by location. When I run the following code in arcpy, it converts all rows in the field Present
to 1.
pts = "points"
poly = "poly"
fieldname = "Present" arcpy.management.SelectLayerByLocation(pts, "INTERSECT", poly, None, "NEW_SELECTION", "NOT_INVERT")
arcpy.management.CalculateField(pts, fieldname, "1", "PYTHON3", '',"TEXT")
My question is similar to Using select by attributes then calculate field on selection in ArcPy?, which is for select by attribute. I am assuming the answer is close to this code.
pts = "points"
poly = "poly"
fieldname = "Present"
arcpy.management.SelectLayerByLocation(pts, "INTERSECT", poly, None, "NEW_SELECTION", "NOT_INVERT")
sql = """{0} = ''""".format(arcpy.AddFieldDelimiters(pts,fieldname)) ### this is wrong
with arcpy.da.UpdateCursor(fc,fieldname,sql) as cursor:
for row in cursor:
row[0] = 1
cursor.updateRow(row)
I basically want to set row to 1 (default is 0), when the point is selected.
I think you are misunderstanding the answer in Using select by attributes then calculate field on selection in ArcPy? - This question is using SelectLayerByAttributes()
and the answer is replacing the Selection with the SQL query.
You are not using SelectLayerByAttributes, so the SQL query won't do anything for you here.
Both of your examples should work - CalculateField and UpdateCursor will both honor the selection set and process only selected features, but only if you pass the Layer to the tool. If you pass the Feature Class then they will process every feature. See Using UpdateCursor based on current selection of features.
pts = "MyPointsLayer"
poly = "MyPolygons"
fieldname = "Present"
arcpy.management.SelectLayerByLocation(pts, "INTERSECT", poly, None, "NEW_SELECTION", "NOT_INVERT")
arcpy.management.CalculateField(pts, fieldname, "1", "PYTHON3", '',"TEXT")
pts = "MyPointsLayer"
poly = "MyPolygons"
fieldname = "Present"
arcpy.management.SelectLayerByLocation(pts, "INTERSECT", poly, None, "NEW_SELECTION", "NOT_INVERT")
with arcpy.da.UpdateCursor(pts,fieldname) as cursor:
for row in cursor:
row[0] = 1
cursor.updateRow(row)
Notice that both tools are pointed at pts
which refers to your layer. In the example in your question you had the UpdateCursor pointing to fc
.
Answered by Midavalo on November 1, 2021
Get help from others!
Recent Answers
Recent Questions
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP