2

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)

enter image description here

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?

Vince
20.5k16 gold badges49 silver badges65 bronze badges
asked Mar 13, 2023 at 18:41
2
  • 2
    If you're searching for "Unknown", then then "UNKNOWN" won't match it (case sensitive comparison). Always use 4 spaces for your indent rule (see PEP 8). You don't handle the case where both are UNKNOWN. Commented Mar 13, 2023 at 19:07
  • You are updating all rows since cursor.updateRow(row) is not indentated to match the ifs Commented Mar 14, 2023 at 9:30

2 Answers 2

1

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)

index, count

enter image description here

answered Mar 13, 2023 at 18:49
0

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.

answered Mar 14, 2023 at 9:19

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.