2

I need to change values in field "name1" (string field) in specific rows: 70-72 into "no land use" value. I search Arcpy code to do it.

i red How to select specific row in attribute table using ArcPy (without iterating through whole table)? but didn't understand what shoud i do.

I using this code:

import arcpy

lyrName = r"G:\PROJECTS\herzel138\gis\layers\New File Geodatabase.gdb\digum2"
with arcpy.da.UpdateCursor(lyrName, ["name1"]) as cursor:
    for row in cursor:
        if row == 70 and row ==71 and row ==72:
            row[0] = 'no land use'
            cursor.updateRow(row)
            print "Processing complete"
        else:
            print 'nothing founded'

enter image description here

but i get no result:

enter image description here

  • name1 field type text – newGIS Jan 4 '18 at 9:10
3

You must check the value of the OBJECTID field, not the row object:

import arcpy

lyrName = r"G:\PROJECTS\herzel138\gis\layers\New File Geodatabase.gdb\digum2"
with arcpy.da.UpdateCursor(lyrName, ["name1", "OID@"]) as cursor:
    for row in cursor:
        if row[1] in (70, 71, 72):
            row[0] = 'no land use'
            cursor.updateRow(row)
            print """Updated row {}""".format(row[1])

The OID@ token refers to the OBJECTID field, no matter how it's called (this may vary depending on the dataset format - file gdb, shapefile, enterprise gdb...). See the arcpy.da.UpdateCursor help page for reference.

2

As a complement to the answer provided you dont need to iterate over every row in the table. In your case you could specify a where_clause in the cursor to only iterate over OIDs 70-72 and then update them without an if statement.

import arcpy
lyrName = r"G:\PROJECTS\herzel138\gis\layers\New File Geodatabase.gdb\digum2"
sql = """{0} IN (70,71,72)""".format(arcpy.Describe(lyrName).OIDFieldName)
with arcpy.da.UpdateCursor(in_table=lyrName, field_names='name1', where_clause=sql) as cursor:
    for row in cursor:
        row[0]='no land use'
        cursor.updateRow(row)
  • This is indeed more efficient/elegant :) But unless there are at least 100 000s of rows the performance gain will not be noticeable I think – GISGe Jan 4 '18 at 9:34
  • I agree, I usually dont bother using a where_clause since the cursor is so fast anyway – BERA Jan 4 '18 at 9:36
  • 1
    If there is an index on 1000 or more rows, where_clause use will always be noticeably faster. Constraining the query to return only the required rows is always best practice. – Vince Jan 4 '18 at 13:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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