Here's what I'm trying to do.
I have a shapefile called 'Roster' with an attribute table like the one below.
NAME | Age | Room |
---|---|---|
***John | 23 | B |
***Alice | 56 | C |
Tina | 34 | A |
I would like to search the shapefile and delete any data under the field 'NAME' where the string starts with '***'
The resulting table would look like this
NAME | Age | Room |
---|---|---|
23 | B | |
56 | C | |
Tina | 34 | A |
I figured out how to replace the '***' string with another string, but I can't figure out how to delete the entire cell....
def removeName(shapefilePath):
cursor = arcpy.da.UpdateCursor(shapefilePath, ["NAME"])
for row in cursor:
row[0] = row[0].replace("***", None)
cursor.updateRow(row)
del row
del cursor
Solved! Go to Solution.
Thank you both for your help.
The code worked once I changed cursor.update(row) to cursor.updateRow(row)
Here is the final code
def removeName(shapefilePath):
cursor = arcpy.da.UpdateCursor(shapefilePath, ["NAME"])
for row in cursor:
nameStr = row[0]
if nameStr[0:3] == "***":
row[0] = ""
cursor.updateRow(row)
del row
del cursor
Replace the contents of the for block with:
nameStr = row[0]
if nameStr[0:3] == "***" then:
newName = nameStr.replace("***", None)
row[0] = newName
cursor.update(row)
nameStr = row[0]
if nameStr[0:3] == "***" then:
# This is if you wanted to just strip the ***
newName = nameStr.replace("***", None)
row[0] = newName
# set the string to nothing
row[0] = ""
cursor.update(row)
def removeName(shapefilePath):
cursor = arcpy.da.UpdateCursor(shapefilePath, ["NAME"])
for row in cursor:
nameStr = row[0]
if nameStr[0:3] == "***" :
row[0] = ""
cursor.update(row)
Thank you both for your help.
The code worked once I changed cursor.update(row) to cursor.updateRow(row)
Here is the final code
def removeName(shapefilePath):
cursor = arcpy.da.UpdateCursor(shapefilePath, ["NAME"])
for row in cursor:
nameStr = row[0]
if nameStr[0:3] == "***":
row[0] = ""
cursor.updateRow(row)
del row
del cursor
Although I am thinking the UpdateCursor (arcpy.da) might still be faster, one could also use Make Feature Layer or Select Layer By Attribute followed by Calculate Field. My preference is usually arcpy, but there are other geoprocessing ways of accomplishing the same task.
def removeName(shapefilePath):
arcpy.MakeFeatureLayer_management(shapefilePath, "shapefileLayer",
' "NAME" LIKE \'***%\' ')
arcpy.CalculateField_management("shapefileLayer", "NAME", "str()", "PYTHON_9.3")
Thanks Ian--I've been writing VBA lately...
I figured it was something like that Charlie, no worries
Another way to see if the name starts with ***
def removeName(shapefilePath):
cursor = arcpy.da.UpdateCursor(shapefilePath, ["NAME"])
for row in cursor:
nameStr = row[0]
if nameStr.startswith("***"):
row[0] = ""
cursor.updateRow(row)
del row
del cursor
R_