1

How can I delete a row in a table if value A from Field 1 does not match value B from Field 4 ?

I attempted to use code from a previous post as I figured it would be a start but didn't work.

enter image description here

import arcpy
shp = r"C:\path\to\your\shapefile.shp"
rows = arcpy.UpdateCursor(shp, "", "", "some_field")
for row in rows:
    if row.some_field == 2:
        rows.deleteRow(row)
del row
del rows
4
  • 1
  • Im a newbie with ArcPy so would the does not equal be written as so? import arcpy fc = r'C:\temp\test.gdb\tmp' with arcpy.da.UpdateCursor(fc, "Value_1","Value_4") as cursor: for row in cursor: if row[0] <> row[1]: cursor.deleteRow()
    – huskersila
    Aug 10, 2016 at 23:37
  • 1
    If that doesn't work use row[0] != row[1]
    – Bjorn
    Aug 11, 2016 at 0:03
  • 1
    Your second parameter needs to be a list of field names. Right now you have a field name referenced in both the second and third parameter. (fc, ["Value_1", "Value_2"])
    – artwork21
    Aug 11, 2016 at 0:28

2 Answers 2

4

I would begin by creating a copy of the original feature class. Then it is simply a matter of checking if row[0] (i.e. Value_1 field) is equivalent to row[1] (Value_4 field). Try the following approach:

import arcpy

in_shp = r"C:\path\to\your\shapefile.shp"
shp_copy = r"C:\path\to\your\shapefile_v2.shp"

# Make a copy!
arcpy.CopyFeatures_management(in_shp, shp_copy)

# Check if "Value_1" is equivalent to "Value_4", if not delete row
with arcpy.da.UpdateCursor(shp_copy, ["Value_1", "Value_4"]) as cursor:
    for row in cursor:
        if row[0] != row[1]:
            cursor.deleteRow()
4
  • I attempted script and added image of error. Does it matter that its a table and not a shapefile?
    – huskersila
    Aug 11, 2016 at 2:07
  • @huskersila You need to make sure to name the copy different than the original.
    – Aaron
    Aug 11, 2016 at 2:15
  • ty for the help .... I ended up getting one of the above scripts to work... ty again for your time! much appreciated!! import arcpy fc = r'C:\Users\FILEPATH' with arcpy.da.UpdateCursor(fc,["VALUE_1","VALUE_4"]) as cursor: for row in cursor: if row[0] != row[1]: cursor.deleteRow()
    – huskersila
    Aug 11, 2016 at 2:24
  • @huskersila if this has worked for you please mark as the answer. See What should I do when someone answers my question?
    – Midavalo
    Aug 11, 2016 at 2:47
1
import arcpy

fc = r'C:\Users\FILEPATH'
with arcpy.da.UpdateCursor(fc, ["VALUE_1","VALUE_4"]) as cursor:
  for row in cursor:
    if row[0] != row[1]:
      cursor.deleteRow()

Your Answer

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

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