delete rows in feature classes where some of the fields contain zero (0)

5608
5
02-05-2015 05:42 AM
ErtTre
by
New Contributor II

Hi,

So far I got this far:

import arcpy 

from arcpy import env 

env.workspace = r"C:\SouthA\Bolivia.gdb" 

listFCs = arcpy.ListFeatureClasses("*")

for fc in listFCs:

     rows = arcpy.UpdateCursor(fc, , , ["field1", "field2", "field6", "field7"])

     for row in rows:

          if row.getValue() == 0:

          rows.deleteRow(row)

The idea is that in each table select and delete the rows which have "0"s in either/or  field1, field2....

Thanks

Ert

0 Kudos
5 Replies
JoshuaBixby
MVP Esteemed Contributor

For starters, I encourage you to read up on the Arcpy Data Access module (arcpy.da).  The cursors in the data access module are newer, more robust, and higher performing than the older cursors.

I gotta step out but will post some code when I get back if someone hasn't already.

JoshuaBixby
MVP Esteemed Contributor

Haven't tested, but try:

import arcpy  
from arcpy import env  
env.workspace = r"C:\SouthA\Bolivia.gdb" 

listFCs = arcpy.ListFeatureClasses("*")
for fc in listFCs:
    with arcpy.da.UpdateCursor(fc, ["field1", "field2", "field6", "field7"]) as cur:
        for row in cur:
            if 0 in row:
                cur.deleteRow()
BlakeTerhune
MVP Regular Contributor

Instead of checking each row to see if it meets the condition, could you only bring back the rows that meet the condition and delete them all?

import arcpy

arcpy.env.workspace = r"C:\SouthA\Bolivia.gdb"

listFCs = arcpy.ListFeatureClasses("*")
field_names = ["field1", "field2", "field6", "field7"]
where_clause = "field1 = 0 OR field2 = 0 OR field6 = 0 OR field7 = 0"
for fc in listFCs:
    with arcpy.da.UpdateCursor(fc, field_names, where_clause) as cur:
        for row in cur:
            cur.deleteRow()
JoshuaBixby
MVP Esteemed Contributor

That is another approach.  Although I like working with SQL, building SQL expressions via Python and passing them to Esri tools seems to be a hang up for lots of folks, so I decided against suggesting a where_clause, but it will work.

ErtTre
by
New Contributor II

Thanks Guys,

Both ideas worked!

0 Kudos