I'm new to ArcPy. I am attempting to find the string 'Unknown' and update the 'Comments' field, that indicates which field contains the 'Unknown' string for that row. I was attempting to use UpdateCursor but it populates every row under comments rather then just the specific row that contains the string.
points = r'C:/ex.shp'
fields= ['COMMENTS', 'COUNTY', 'STATUS']
with arcpy.da.UpdateCursor(points, fields) as cursor:
for row in cursor:
if row[1] == 'UNKNOWN':
row[0] = 'County is Unknown'
if row[2] == 'UNKNOWN':
row[0] = 'Status is Unknown'
cursor.updateRow(row)
I understand this won't work since it is checking/updating each row for that specified field. Can someone point me in the right direction on how one would do this properly?
2 Answers 2
Try this:
import arcpy
fc = r"C:\Users\username\AppData\Local\Temp\ArcGISProTemp10292\Untitled\Default.gdb\points1"
fields = ["COMMENTS","COUNTY","STATUS"]
with arcpy.da.UpdateCursor(fc, fields) as cursor:
for row in cursor:
c = row.count("UNKNOWN") #Count how many times UNKNOWN occur in the row
if c==0:
result = "Missing" #If 0, set COMMENT to Missing
elif c==1:
result = f"{fields[row.index('UNKNOWN')]} is Unknown" #If once, fetch the field name from field list using index
elif c==2:
result = f"{fields[1]} and {fields[2]} are both Unknown"
else:
raise ValueError(f"Cant handle this row: {row}") #Just in case something went wrong, stop the execution
row[0] = result
cursor.updateRow(row)
Your code is work. You should use elif
after first if
condition and as Vince said, you should add one more condition.
I think, your problem is – to view the result you must reopen the table.
cursor.updateRow(row)
is not indentated to match the ifs