2

I'm trying to create a piece of code to remove rows where the field "State_Name" equals Hawaii or Alaska from my shapefile's attribute table. I've tried two different codes and they both seem to run without error in the ArcGIS Pro Python window, however the attribute table doesn't change.

First attempt:

with arcpy.da.UpdateCursor(outputft, ["State_Name"]) as cursor:
    for row in cursor:
        where="State_Name is HAWAII or ALASKA"
        cursor.deleteRow()
    

Second attempt:

with arcpy.da.UpdateCursor(outputft, ["State_Name"]) as cursor:
    for row in cursor:
        if row[0] == 'HAWAII':
            cursor.deleteRow()

I've closed, reopened, refreshed the attribute table as well but it doesn't seem to work. I'm new to Python.

1
  • You can't apply a WHERE constraint after the cursor is defined, and the syntax is wrong for SQL. Note that "HAWAII" is not equal to "Hawaii", so the second attempt may correctly fail to find any rows to delete.
    – Vince
    May 11, 2021 at 12:15

1 Answer 1

5

Use a where clause to delete all rows returned by the cursor:

where_clause = "{0} IN('HAWAII', 'ALASKA')".format(arcpy.AddFieldDelimiters(datasource=outputft, field="State_Name"))

with arcpy.da.UpdateCursor(in_table=outputft, field_names="State_Name", where_clause=where_clause) as cursor:
    for row in cursor:
        cursor.deleteRow()
3
  • 1
    Thank you so much! That did the trick.
    – Umbra
    May 11, 2021 at 16:44
  • Nice! I think you second attempt also should work, but it will be slightly slower if you try like this: if row[0] IN('HAWAII', 'ALASKA'):
    – BERA
    May 11, 2021 at 16:45
  • 1
    Good to know, thanks! Now to make the choropleth map... :)
    – Umbra
    May 11, 2021 at 16:46

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.